我有以下代码片段:
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/