From fb13f93b03bb569414f80693a135d4269df294ba 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. --- lib/internal/streams/end-of-stream.js | 6 ++++-- test/parallel/test-stream-finished.js | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/internal/streams/end-of-stream.js b/lib/internal/streams/end-of-stream.js index 8c5cf937df335e..b5508252710f21 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 7dc26dcbeb6afa..a495bbe2861170 100644 --- a/test/parallel/test-stream-finished.js +++ b/test/parallel/test-stream-finished.js @@ -492,3 +492,26 @@ testClosed((opts) => new Writable({ write() {}, ...opts })); .on('response', common.mustCall()); }); } + + +{ + 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); + })); +}