diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 47a9bb208cd5e3..c6d4ec4266f4aa 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -617,10 +617,11 @@ function callFinal(stream, state) { state.pendingcb--; if (err) { errorOrDestroy(stream, err); + } else { + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); }); } function prefinish(stream, state) { diff --git a/test/parallel/test-stream2-writable.js b/test/parallel/test-stream2-writable.js index b20f5d3f18cc13..40277007820007 100644 --- a/test/parallel/test-stream2-writable.js +++ b/test/parallel/test-stream2-writable.js @@ -441,3 +441,20 @@ const helloWorldBuffer = Buffer.from('hello world'); w.write('hello'); w.destroy(new Error()); } + +{ + // Verify that finish is not emitted after error + const w = new W(); + + w._final = common.mustCall(function(cb) { + cb(new Error()); + }); + w._write = function(chunk, e, cb) { + process.nextTick(cb); + }; + w.on('error', common.mustCall()); + w.on('prefinish', common.mustNotCall()); + w.on('finish', common.mustNotCall()); + w.write(Buffer.allocUnsafe(1)); + w.end(Buffer.allocUnsafe(0)); +}