stickfigure stickfigure - 1 year ago 96
Node.js Question

Is console.time() safe in node.js?

I have a little snippet of node.js code in front of me that looks like this:

doAsyncIOBoundThing(function(err, results) {
// Process the results...

And of course when I run this on my (otherwise idle) development system, I get a nice console message like this:

queryTime: 564ms

However, if I put this into production, won't there likely be several async calls in progress simultaneously, and each of them will overwrite the previous timer? Or does node have some sort of magical execution context that gives each "thread of execution" a separate console timer namespace?

Answer Source

Just use unique labels and it will be save. That's why you use a label, to uniquely identify the start time.

The reason for this is quite simple: console.time and console.timeEnd are one of the simplest functions of the world (source):

Console.prototype.time = function(label) {

Console.prototype.timeEnd = function(label) {
  var time = this._times.get(label);
  if (!time) {
    throw new Error('No such label: ' + label);
  var duration = - time;
  this.log('%s: %dms', label, duration);

As long as you don't accidentally use a label twice everything will work exactly as intended. Also note that node has usually only one thread of execution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download