gpt4 book ai didi

node.js - 在写入结果可用之前是否应该注册 `drain` 事件

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:20 25 4
gpt4 key购买 nike

我有这段代码:

const file = fs.createWriteStream('./test.txt');
let written = true;

// handler is added before even an attempt to write is made
file.on('drain', function () {
written = true;
console.log('drained');
});

const interval = setInterval(function () {
if (Date.now() - time > 10000) {
clearInterval(interval);
}

if (written) {
written = file.write(new Array(1000000).join('z'));
}
}, 100);

我想知道是否有添加处理程序(即使尝试写入)的标准做法?

最佳答案

如果使用 file.on('drain') 监听器,您可以设置通用监听器来排出流的事件。注意:关闭可写流后,该监听器将被删除。

通常,该代码可以正常工作,但 Node.js 中最常见的做法是对每种内部缓冲区超出的情况使用 stream.once('drain') 处理程序。 Event: 'drain'Node.js 文档中介绍了该方法。 :

function writeOneMillionTimes(writer, data, encoding, callback) {
var i = 1000000;
write();
function write() {
var ok = true;

do {
i -= 1;
if (i === 0) {
// last time!
writer.write(data, encoding, callback);
} else {
// see if we should continue, or wait
// don't pass the callback, because we're not done yet.
ok = writer.write(data, encoding);
}
} while (i > 0 && ok);

if (i > 0) {
// had to stop early!
// write some more once it drains
writer.once('drain', write);
}
}
}

关于node.js - 在写入结果可用之前是否应该注册 `drain` 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41218186/

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