I have this snippet of code:
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);
I'm wondering if that a standard practice to add handler even an attempt to write is made?
In case of using
file.on('drain')
listener you set up general listener to drain event of your stream. Notice: This listener will be removed after closing of writable stream.Generally that code will work proper, but most common practice in Node.js is to use
stream.once('drain')
handler for each case of internal buffer exceeding. That approach is covered inNode.js
documentation for Event: 'drain':