How to measure http.ClientRequest response time in NodeJS?

544 views
Skip to first unread message

Tihomir Kit

unread,
Nov 18, 2014, 3:26:52 AM11/18/14
to nod...@googlegroups.com
Hi all, 

I posted the following question on SO yesterday but it got little attention so I decided to ask here as well, I hope you don't mind:
http://stackoverflow.com/questions/26977272/how-to-measure-http-clientrequest-response-time-in-nodejs

Here's my problem:


I'm creating http requests from my NodeJS application like this:

var start;

var req = http.request(options, function (res) {
    res.setEncoding('utf8');

    var body = '';
    res.on('data', function (chunk) {
        body += chunk;
    });
    res.on('end', function () {
        var elapsed = process.hrtime(start)[1] / 1000000; // in milliseconds
        console.log(elapsed);
        // whatever
    });
});

req.on('socket', function (res) {
    start = process.hrtime();
});

req.on('error', function (res) {
    // whatever
});

if (props.data) req.write(props.data);
req.end();

I want to find out how long my requests take - starting from (or the closest I can get to) the moment the request has been over the wire (and not the moment that the promise has been created) and up to the moment that "response end" event kicked in.

I'm having a bit of trouble finding out the closest moment / event which I could hook to to start measuring the time. Http client socket event is my best bet so far but its description:

Emitted after a socket is assigned to this request.

doesn't really tell whether that's the event I'm looking for.. So, my question is - am I doing this right or is there a better event I could use (or even a better way of doing the whole thing)? Thanks.


So if anyone is able to help - I am most grateful for any feedback / help. :)


Regards,

Tihomir

Reply all
Reply to author
Forward
0 new messages