Does buffer `console.log` output in node.js?

I wonder if console.log prints buffers in node.js or tries to do IO on every call? This does not seem to be officially documented.

The question arose from the need to output an array of strings, and I think which idiom is more efficient:

 array.forEach(function(line){ console.log(line) }) 

or

 console.log(array.join('\n')) 

thanks

+7
javascript
source share
1 answer

The documentation for console.log() probably does not indicate if it outputs buffers because it delegates this solution to the underlying thread :

 Console.prototype.log = function() { this._stdout.write(util.format.apply(this, arguments) + '\n'); }; 

writable.write() it uses documents for general buffering:

A return value indicates whether to continue writing right now. If the data needs to be buffered internally, then it will return false . Otherwise, it will return true .

This return value is strictly recommended. You MAY keep writing even if it returns false . However, the records will be buffered in memory, so it is best not to do this excessively. Instead, wait for the drain event before writing more data.

Although the global console uses process.stdout , which is more likely to block, it only buffers under certain circumstances:

process.stderr and process.stdout differ from other threads in Node in that entries to them are usually blocked.

  • They are blocked if they refer to regular files or TTY file descriptors.
  • In case they relate to pipes:
    • They are blocked on Linux / Unix.
    • They are not blocked like other threads in Windows.

To check if any .write() were buffered, you could .write() them on stdout yourself and commit the return value:

 var util = require('util'); var buffered = []; array.forEach(function(line){ buffered.push(!process.stdout.write(util.format(line) + '\n')); }); console.log(buffered); 
+6
source share

All Articles