我想知道 console.log
是否在 node.js 中缓冲输出或尝试在每次调用时执行 IO?这似乎没有正式记录。
问题源于输出字符串数组的必要性,我认为哪种习惯用法更有效:
array.forEach(function(line){
console.log(line)
})
或
console.log(array.join('\n'))
谢谢
最佳答案
console.log()
的文档可能没有指定它是否缓冲输出,因为它 delegates that decision to an underlying stream :
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
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
. Otherwise, it will returntrue
.This return value is strictly advisory. You MAY continue to write, even if it returns
false
. However, writes will be buffered in memory, so it is best not to do this excessively. Instead, wait for thedrain
event before writing more data.
不过,全局控制台
使用process.stdout
这更有可能阻塞,仅在某些情况下缓冲:
process.stderr
andprocess.stdout
are unlike other streams in Node in that writes to them are usually blocking.
- They are blocking in the case that they refer to regular files or TTY file descriptors.
- In the case they refer to pipes:
- They are blocking in Linux/Unix.
- They are non-blocking like other streams in Windows.
要查看是否有任何 line
被缓冲,您可以自己将它们 .write()
到 stdout
并捕获返回值:
var util = require('util');
var buffered = [];
array.forEach(function(line){
buffered.push(!process.stdout.write(util.format(line) + '\n'));
});
console.log(buffered);
关于javascript - `console.log` 是否在 node.js 中缓冲输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27529235/