55597 55597 - 3 months ago 19
Node.js Question

Measuring time taken to transfer a file in express server

Is it possible to find the time taken by res.sendFile('filename') to transfer a file? how to do it with the function parameter that I can add to the sendFile function.

Answer

You can install a middleware that will track the time by listening for the finish event on the response object:

app.use(function(req, res, next) {
  var start = Date.now();
  res.on('finish', function() {
    console.log('took %s ms', Date.now() - start);
  });
  next();
});

If you have a specific route that you want to apply this middleware to, you can use something like this:

var timingMiddleware = function(req, res, next) {
  var start = Date.now();
  res.on('finish', function() {
    console.log('%s took %s ms', req.params.filename, Date.now() - start);
  });
  next();
};

app.get('/:filename', timingMiddleware, function(req, res) {
  res.sendFile(req.params.filename);
});
Comments