diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 9b75b672cbd843..35926ad9d43b87 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -309,7 +309,7 @@ Writable.prototype.write = function(chunk, encoding, cb) { } else if (state.destroyed) { const err = new ERR_STREAM_DESTROYED('write'); process.nextTick(cb, err); - errorOrDestroy(this, err); + errorOrDestroy(this, err, true); } else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); diff --git a/lib/internal/streams/destroy.js b/lib/internal/streams/destroy.js index 8708ca022c7f8d..7c4c87bc933053 100644 --- a/lib/internal/streams/destroy.js +++ b/lib/internal/streams/destroy.js @@ -107,7 +107,7 @@ function undestroy() { } } -function errorOrDestroy(stream, err) { +function errorOrDestroy(stream, err, tick) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow @@ -123,8 +123,13 @@ function errorOrDestroy(stream, err) { if ((r && r.autoDestroy) || (w && w.autoDestroy)) stream.destroy(err); - else if (needError(stream, err)) - stream.emit('error', err); + else if (needError(stream, err)) { + if (tick) { + process.nextTick(emitErrorNT, stream, err); + } else { + stream.emit('error', err); + } + } }