Skip to content

Commit bd05183

Browse files
committed
stream: avoid unecessary nextTick
If we are not going to emit 'close' then there is no reason to schedule it. PR-URL: nodejs#29194 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Backport-PR-URL: nodejs#29691
1 parent 3d88b76 commit bd05183

File tree

1 file changed

+17
-15
lines changed

1 file changed

+17
-15
lines changed

lib/internal/streams/destroy.js

+17-15
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,25 @@ function destroy(err, cb) {
3535
}
3636

3737
this._destroy(err || null, (err) => {
38+
const emitClose = (this._writableState && this._writableState.emitClose) ||
39+
(this._readableState && this._readableState.emitClose);
3840
if (!cb && err) {
3941
if (!this._writableState) {
40-
process.nextTick(emitErrorAndCloseNT, this, err);
42+
const emitNT = emitClose ? emitErrorAndCloseNT : emitErrorNT;
43+
process.nextTick(emitNT, this, err);
4144
} else if (!this._writableState.errorEmitted) {
4245
this._writableState.errorEmitted = true;
43-
process.nextTick(emitErrorAndCloseNT, this, err);
44-
} else {
46+
const emitNT = emitClose ? emitErrorAndCloseNT : emitErrorNT;
47+
process.nextTick(emitNT, this, err);
48+
} else if (emitClose) {
4549
process.nextTick(emitCloseNT, this);
4650
}
4751
} else if (cb) {
48-
process.nextTick(emitCloseNT, this);
52+
if (emitClose) {
53+
process.nextTick(emitCloseNT, this);
54+
}
4955
cb(err);
50-
} else {
56+
} else if (emitClose) {
5157
process.nextTick(emitCloseNT, this);
5258
}
5359
});
@@ -56,18 +62,18 @@ function destroy(err, cb) {
5662
}
5763

5864
function emitErrorAndCloseNT(self, err) {
59-
emitErrorNT(self, err);
60-
emitCloseNT(self);
65+
self.emit('error', err);
66+
self.emit('close');
6167
}
6268

6369
function emitCloseNT(self) {
64-
if (self._writableState && !self._writableState.emitClose)
65-
return;
66-
if (self._readableState && !self._readableState.emitClose)
67-
return;
6870
self.emit('close');
6971
}
7072

73+
function emitErrorNT(self, err) {
74+
self.emit('error', err);
75+
}
76+
7177
function undestroy() {
7278
if (this._readableState) {
7379
this._readableState.destroyed = false;
@@ -87,10 +93,6 @@ function undestroy() {
8793
}
8894
}
8995

90-
function emitErrorNT(self, err) {
91-
self.emit('error', err);
92-
}
93-
9496
function errorOrDestroy(stream, err) {
9597
// We have tests that rely on errors being emitted
9698
// in the same tick, so changing this is semver major.

0 commit comments

Comments
 (0)