From 5274a8f7db972af7043f85955877047a039e6462 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Sun, 20 Nov 2022 14:42:47 +0100 Subject: [PATCH] stream: avoid premature close when will not emit close Fixes: https://github.com/nodejs/node/issues/45281 PR-URL: https://github.com/nodejs/node/pull/45301 Reviewed-By: Luigi Pinca Reviewed-By: Matteo Collina Reviewed-By: Benjamin Gruenbaum Reviewed-By: Minwoo Jung --- lib/internal/streams/end-of-stream.js | 20 ++++++++++++++++---- test/parallel/test-stream-finished.js | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/lib/internal/streams/end-of-stream.js b/lib/internal/streams/end-of-stream.js index ba565a9ae52323..ca42174c86459a 100644 --- a/lib/internal/streams/end-of-stream.js +++ b/lib/internal/streams/end-of-stream.js @@ -151,6 +151,18 @@ function eos(stream, options, callback) { callback.call(stream); }; + const onclosed = () => { + closed = true; + + const errored = isWritableErrored(stream) || isReadableErrored(stream); + + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored); + } + + callback.call(stream); + }; + const onrequest = () => { stream.req.on('finish', onfinish); }; @@ -186,22 +198,22 @@ function eos(stream, options, callback) { process.nextTick(onclose); } else if (wState?.errorEmitted || rState?.errorEmitted) { if (!willEmitClose) { - process.nextTick(onclose); + process.nextTick(onclosed); } } else if ( !readable && (!willEmitClose || isReadable(stream)) && (writableFinished || isWritable(stream) === false) ) { - process.nextTick(onclose); + process.nextTick(onclosed); } else if ( !writable && (!willEmitClose || isWritable(stream)) && (readableFinished || isReadable(stream) === false) ) { - process.nextTick(onclose); + process.nextTick(onclosed); } else if ((rState && stream.req && stream.aborted)) { - process.nextTick(onclose); + process.nextTick(onclosed); } const cleanup = () => { diff --git a/test/parallel/test-stream-finished.js b/test/parallel/test-stream-finished.js index a574a4a65342e2..c7513805e7ac6f 100644 --- a/test/parallel/test-stream-finished.js +++ b/test/parallel/test-stream-finished.js @@ -667,3 +667,17 @@ testClosed((opts) => new Writable({ write() {}, ...opts })); ).end(); }); } + +{ + const stream = new Duplex({ + write(chunk, enc, cb) { + setImmediate(cb); + } + }); + + stream.end('foo'); + + finished(stream, { readable: false }, common.mustCall((err) => { + assert(!err); + })); +}