-2

Threw nodejs,I have a problem in calculating express api response time.

instead of using middlewares like morgan and winston using app.use(). I need a way to log response time inside api scope and send it as a response. like :

app.post('/api', function (req: Request, res:Response) {
...
res.json({responseTime,data})
})

I have tried response-time package and stackoverflow question solutions but they were not helpful.

In fast responses that take less than 100ms, I see different response time in postman and my node server console.(e.g. postman:130ms , node server: 3ms)

how can I calculate the response time accurately?

Reza Ghorbani
  • 537
  • 4
  • 14
  • How do you plan on measuring response time from within your server, exactly? How could your server possibly take into account how long it takes for the data to be sent and then return to the client over the wire? – esqew Oct 21 '22 at 19:37
  • you are right. by trying many ways I thinks that middlewares like `morgan` are more accurate in measuring response time. but I need to have this time inside my api – Reza Ghorbani Oct 21 '22 at 19:43

1 Answers1

1

There are different ways to use it. But one way of the ways most used is using morgan. Of course, you can see response time on only dev mode.

const morgan = require('morgan');


app.use(morgan('dev'));

After you added like that, you should see a screen like that on terminal. enter image description here

Halil
  • 211
  • 2
  • 7
  • I need a way to log response time inside api scope inside an object that I send as a response, instead of app.use(). – Reza Ghorbani Oct 21 '22 at 19:00
  • @RezaGhorbani Why doesn't response-time package help you ? I have just searched for your question and I found response-time package to use. They used it like a middleware – Halil Oct 23 '22 at 19:48