简体   繁体   English

在node.js中`console.log`缓冲区输出吗?

[英]Does `console.log` buffer output in node.js?

I wonder if console.log buffers output in node.js or tries to perform IO on each invocation? 我想知道console.log缓冲node.js中的输出还是尝试在每次调用时执行IO? This doesn't seem to be officially documented. 这似乎没有正式记录。

The question arose from the necessity 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 谢谢

The documentation for console.log() probably doesn't specify whether it buffers output because it delegates that decision to an underlying stream : console.log()的文档可能没有指定它是否缓冲输出,因为它将该决策委托给基础流

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

The writable.write() it's using documents the general possibility of buffering: writable.write()它正在使用文档缓冲的一般可能性:

The return value indicates if you should continue writing right now. 返回值表示您是否应该立即继续写作。 If the data had to be buffered internally, then it will return false . 如果数据必须在内部缓冲,那么它将返回false Otherwise, it will return true . 否则,它将返回true

This return value is strictly advisory. 这个返回值是严格的建议。 You MAY continue to write, even if it returns false . 你可以继续写,即使它返回false However, writes will be buffered in memory, so it is best not to do this excessively. 但是,写入将缓冲在内存中,因此最好不要过度执行此操作。 Instead, wait for the drain event before writing more data. 相反,在写入更多数据之前等待drain事件。

Though, the global console uses process.stdout that's more likely to block, buffering only under certain circumstances: 但是,全局console使用的process.stdout更可能阻止,仅在某些情况下缓冲:

process.stderr and process.stdout are unlike other streams in Node in that writes to them are usually blocking. process.stderrprocess.stdout与Node中的其他流不同,对它们的写入通常是阻塞的。

  • They are blocking in the case that they refer to regular files or TTY file descriptors. 如果它们引用常规文件或TTY文件描述符,它们就会阻塞。
  • In the case they refer to pipes: 在他们引用管道的情况下:
    • They are blocking in Linux/Unix. 它们在Linux / Unix中受阻。
    • They are non-blocking like other streams in Windows. 它们像Windows中的其他流一样是非阻塞的。

To see whether any line s are buffered, you could .write() them to stdout yourself and capture the return value: 要查看是否缓冲了任何line ,您可以.write()它们自己.write()stdout并捕获返回值:

var util = require('util');
var buffered = [];

array.forEach(function(line){
  buffered.push(!process.stdout.write(util.format(line) + '\n'));
});

console.log(buffered);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM