Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time requests in NodeJS/Express

What would be the best way to time all requests coming into my node app? Basically I want to get the current timestamp at the very beginning of the request and then again at the very end of the request, get the difference and log it. Recommendations on the best way to do this in NodeJS and Express?

Here is a sample of what my app looks like (although a lot more complex than this).

var express = require('express'),
    http = require('http'),
    app = express();

app.get('/', function (req, res, next) {
    res.send(200, 'hi');
});

app.get('/about', function(req, res, next) {
   res.send(200, 'something else');
});

var server = http.createServer(app);
server.listen(9000);
console.log("Express server listening...");

I want to time ALL requests. So I want to time / and /about and anything other endpoint I might add.

like image 338
tbeauvais Avatar asked Aug 30 '13 17:08

tbeauvais


2 Answers

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.

like image 183
Trevor Dixon Avatar answered Oct 02 '22 09:10

Trevor Dixon


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
like image 25
JohnnyHK Avatar answered Oct 02 '22 09:10

JohnnyHK