diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 9a01cb1c06cd4b..e212881c4ac555 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -479,15 +479,17 @@ function onwrite(stream, er) { } if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); + process.nextTick(afterWrite, stream, state, cb); } else { - afterWrite(stream, state, finished, cb); + afterWrite(stream, state, cb); } } } -function afterWrite(stream, state, finished, cb) { - if (!finished && state.length === 0 && state.needDrain) { +function afterWrite(stream, state, cb) { + const needDrain = !state.ending && !stream.destroyed && state.length === 0 && + state.needDrain; + if (needDrain) { state.needDrain = false; stream.emit('drain'); } diff --git a/test/parallel/test-stream-write-drain.js b/test/parallel/test-stream-write-drain.js new file mode 100644 index 00000000000000..bd65c1fdbb8a15 --- /dev/null +++ b/test/parallel/test-stream-write-drain.js @@ -0,0 +1,16 @@ +'use strict'; +const common = require('../common'); +const { Writable } = require('stream'); + +// Don't emit 'drain' if ended + +const w = new Writable({ + write(data, enc, cb) { + process.nextTick(cb); + }, + highWaterMark: 1 +}); + +w.on('drain', common.mustNotCall()); +w.write('asd'); +w.end();