Time requests in NodeJS/Express

This might do the trick: http://www.senchalabs.org/connect/responseTime.html

app.use(express.responseTime());

Or do something like this:

app.use(function(req, res, next) { req.start = Date.now(); next(); });

app.get(...);
app.get(...);

app.use(function(req, res) { var time = Date.now() - req.start; });

This requires that all your routes call next().

Or maybe this (same thing as responseTime middleware, but doesn't set a header):

app.use(function(req, res, next) {
    var start = Date.now();
    res.on('header', function() {
        var duration = Date.now() - start;
        // log duration
    });
    next();
});

header event is fired by Connect middleware in express which is removed as of version 4. Follow this answer for solution - https://stackoverflow.com/a/27348342/4969957

Instead of listening for the 'header' event on res which fires once the headers are sent, you can listen for the 'finish' event, depending on what you want to measure.


you can add to your middleware the module morgan and use it like this-

const morgan = require('morgan')
...
...
const app = express()
app.use(morgan('dev'))

Then the logs will look like this:

// :method :url :status :response-time ms - :res[content-length]
GET /myroute 200 339.051 ms - 242

Check morgan :)


You can use the built-in console.time and console.timeEnd functions for this:

console.time('handler name');
... handle the request
console.timeEnd('handler name');

Output to console:

handler name: 62ms