diff --git a/lib/internal/streams/destroy.js b/lib/internal/streams/destroy.js index 0d3eb6327b9d75..27985482cee70b 100644 --- a/lib/internal/streams/destroy.js +++ b/lib/internal/streams/destroy.js @@ -48,12 +48,15 @@ function destroy(err, cb) { } this._destroy(err || null, (err) => { + const emitClose = (w && w.emitClose) || (r && r.emitClose); if (cb) { - process.nextTick(emitCloseNT, this); + if (emitClose) { + process.nextTick(emitCloseNT, this); + } cb(err); } else if (needError(this, err)) { - process.nextTick(emitErrorAndCloseNT, this, err); - } else { + process.nextTick(emitClose ? emitErrorCloseNT : emitErrorNT, this, err); + } else if (emitClose) { process.nextTick(emitCloseNT, this); } }); @@ -61,22 +64,19 @@ function destroy(err, cb) { return this; } -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); +function emitErrorCloseNT(self, err) { + self.emit('error', err); + self.emit('close'); } function emitCloseNT(self) { - const r = self._readableState; - const w = self._writableState; - - if (w && !w.emitClose) - return; - if (r && !r.emitClose) - return; self.emit('close'); } +function emitErrorNT(self, err) { + self.emit('error', err); +} + function undestroy() { const r = this._readableState; const w = this._writableState; @@ -100,10 +100,6 @@ function undestroy() { } } -function emitErrorNT(self, err) { - self.emit('error', err); -} - function errorOrDestroy(stream, err) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major.