Should `drain` event be registered before the result of the write is available

958 views Asked by At

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?

1

There are 1 answers

0
Ivan Matveev On BEST ANSWER

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 in Node.js documentation for Event: '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);
        }
    }
}