David Portabella David Portabella - 5 months ago 48
Node.js Question

nodejs request library, get the response time

Using the nodejs

request
library: https://github.com/mikeal/request

var request = require('request');
request('http://example.com', function (error, response, body) {
...
})


Is it possible to get the response time on the callback?
The doc mentions response.statusCode. looking at the library source code I also see undocumented response.headers and response.href, but I don't see responseTime or similar.

or, is there an alternative library to
request
that provides the response time?

ps: I know I could do something like this, but that's not a solution, as I am making many async requests and I cannot control when each request will be started.

var request = require('request');
var start = new Date();
request('http://example.com', function (error, response, body) {
...
var responseTime = new Date() - start;
})

Answer

Something like

var timedReq = function(url, next) {
  var start = new Date();
  request(url, function(err, res, body) {
    res.responseTime = new Date() - start;
    next(err, res, body);
  });
};

will do it for you. This seems small enough that it's probably easier than finding a new library.