gpt4 book ai didi

javascript - `console.log` 是否在 node.js 中缓冲输出?

转载 作者:数据小太阳 更新时间:2023-10-29 04:42:18 25 4
gpt4 key购买 nike

我想知道 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 return true.

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 the drain event before writing more data.

不过,全局控制台使用process.stdout这更有可能阻塞,仅在某些情况下缓冲:

process.stderr and process.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com