node.js + mikeal/request - how to measure request time?

I'm using mikeal/request library to access WebAPI. I would like to log to console execution time of every request.

I have multiple and nested requests, so I don't want to put into every single one: var start = Date.now(); ... var time = Date.now() - start; console.log('Finished in '+time+' ms');

I wish there was a possibility of doing something like this: requestWithDefaults = request.defaults({ ... startTime: null }); requestWithDefaults.on('request.prepare', function () { startTime = Date.now(); }); requestWithDefaults.on('request.finished', function () { var time = Date.now() - startTime; console.log('Finished in '+time+' ms'); });

But I don't know how to hook into those moments. Is it somehow possible in a simple way?

If you're looking to just log duration of some process, you could use the built in Node.js console.time() and console.timeEnd() functions. You can check out the Node console docs here.

You could write a small module to wrap requests functionality and add in the console.time[End] statements that could look like:

var request = require('request');

module.exports = {
    get: function(url, next) {
        // start console timer
        console.time(url);
        request.get(url, function() {
            // end console timer
            console.timeEnd(url);
            next.apply(this, arguments);
        });
    }
};

You would then include this module instead of the request module directly and that would give you that logging by default. Note: this is only an example for GET requests, the rest could be built out.

This outputs in the format [label]: 475ms. So pretty nice and really clean to show how many ms it takes for something to complete. This wont give you the nice formatting possibilities from moment.js but it sure is simple.