How to get the response time in node js

10,566

Solution 1

For getting the response time in your routes -

var start = new Date();

router.get('/dummy', function(req, res, next){
    console.log('Request took:', new Date() - start, 'ms');
});

output ex - Request took: 1596 ms

Solution 2

You can pass a function that will get called after a request:

app.use(responseTime((req, res, time) => {
  console.log(req.method, req.url, time + 'ms');
}));

Or use a more elaborate logger middleware like morgan that also provides the option to log response times.

Share:
10,566

Related videos on Youtube

MMR
Author by

MMR

ASK LEARN THEN ANSWER THEN BECOME EXPERT

Updated on June 04, 2022

Comments

  • MMR
    MMR about 2 years

    Recently I started putting response time to my API's.I tried putting to my routes but I am not sure how to use it.My aim is to get the response time in the console for each request.

    var responseTime = require('response-time')
    app.use(responseTime());
    app.route('/getAllUsers').get(users.getUsers); 
    

    Can anyone please suggest help.Thanks.

    • manelescuer
      manelescuer about 7 years
      I've never used response-time module, but I guess you should look at your headers response to see elapsed time.
  • robertklep
    robertklep about 7 years
    That shows the time between the start of the server and the time the request came in. Not very useful.
  • MMR
    MMR about 7 years
    Hi robertklep,how can I print timeslap for every http request i see in console.
  • robertklep
    robertklep about 7 years
    I assume you mean timestamp? console.log(new Date(), req.method, req.url, time + 'ms'). But if you want that, I really recommend using a proper logging module like the aforementioned morgan.
  • MMR
    MMR about 7 years
    I am trying to put timestamp for all requests that I see in the console.