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

标签 javascript node.js

我想知道 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/

相关文章:

javascript - 如何在我的头脑中的链接元素之前添加元元素

javascript - 基于refs的动画在componentDidUpdate中调用setState

javascript - HTML/Javascript 单选按钮测验

javascript - JavaScript 中的正则表达式,如果使用后跟问号的分组,则始终为 ‘undefined’

node.js - 如何从 firebase 函数中的 "get request"获取参数?

javascript - vue 中的 EventBus 不工作

javascript - vueJS点击事件不起作用

php - SocketIO 和 Apache

javascript - 限制发布请求的数量(Javascript + node.js + jQuery)

javascript - 如何根据使用选择框选择的值从数据库中检索特定记录?