在写入结果可用之前应该注册“漏极”事件

我有这段代码:

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')监听器的情况下,您将设置一般监听器来排除您的stream的事件。 注意:closures可写入stream后,此侦听器将被删除。

一般情况下,代码将正常工作,但在Node.js中最常见的做法是使用stream.once('drain')处理程序的每个超过内部缓冲区的情况。 Node.js文档中介绍了这种方法:“drain” :

 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); } } }