From ab130e929aed94739ec879682fa60e786a7865d0 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Sun, 27 Dec 2020 21:48:40 +0100 Subject: [PATCH] stream: only use legacy close listeners if not willEmitClose Some streams that willEmitClose unecessarily fallback to legacy events. PR-URL: https://github.com/nodejs/node/pull/36649 Reviewed-By: Matteo Collina Reviewed-By: Benjamin Gruenbaum Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca --- lib/internal/streams/end-of-stream.js | 6 ++++-- test/parallel/test-stream-finished.js | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/internal/streams/end-of-stream.js b/lib/internal/streams/end-of-stream.js index 29c0171a4f2b1f..0d7067cd9caf6b 100644 --- a/lib/internal/streams/end-of-stream.js +++ b/lib/internal/streams/end-of-stream.js @@ -129,7 +129,9 @@ function eos(stream, options, callback) { if (isRequest(stream)) { stream.on('complete', onfinish); - stream.on('abort', onclose); + if (!willEmitClose) { + stream.on('abort', onclose); + } if (stream.req) onrequest(); else stream.on('request', onrequest); } else if (writable && !wState) { // legacy streams @@ -138,7 +140,7 @@ function eos(stream, options, callback) { } // Not all streams will emit 'close' after 'aborted'. - if (typeof stream.aborted === 'boolean') { + if (!willEmitClose && typeof stream.aborted === 'boolean') { stream.on('aborted', onclose); } diff --git a/test/parallel/test-stream-finished.js b/test/parallel/test-stream-finished.js index 6b2cf430527537..5d357454790e81 100644 --- a/test/parallel/test-stream-finished.js +++ b/test/parallel/test-stream-finished.js @@ -473,3 +473,25 @@ testClosed((opts) => new Writable({ write() {}, ...opts })); finished(p, common.mustNotCall()); })); } + +{ + const w = new Writable({ + write(chunk, encoding, callback) { + process.nextTick(callback); + } + }); + w.aborted = false; + w.end(); + let closed = false; + w.on('finish', () => { + assert.strictEqual(closed, false); + w.emit('aborted'); + }); + w.on('close', common.mustCall(() => { + closed = true; + })); + + finished(w, common.mustCall(() => { + assert.strictEqual(closed, true); + })); +}