From 03a2cbcad82e337e1b2ea7fa2ea1d413d735758f Mon Sep 17 00:00:00 2001 From: rudy-07 Date: Thu, 12 Nov 2026 02:53:20 +0530 Subject: [PATCH] stream: do not detach error listener when stream is already destroyed When an async iterator runs on a Readable stream with autoDestroy: false that was destroyed before iteration started, finalize() took the detach branch because autoDestroy was false. This called cleanup(), removing the eos error listener before the stream's asynchronous _destroy completed. When _destroy subsequently finished, emitErrorNT emitted an unhandled 'error' event on a stream with no listeners, crashing the process even though the iteration error was caught by the consumer. Allow already-destroyed streams to take the finalize path without prematurely detaching the error listener. Fixes: https://github.com/nodejs/node/issues/67418 Signed-off-by: rudy-07 --- lib/internal/streams/readable.js | 2 +- .../test-stream-readable-async-iterators.js | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/internal/streams/readable.js b/lib/internal/streams/readable.js index 9bd7ea636919..81228a7832b1 100644 --- a/lib/internal/streams/readable.js +++ b/lib/internal/streams/readable.js @@ -1613,7 +1613,7 @@ function createAsyncIterator(stream, options) { if ( (error || options?.destroyOnReturn !== false) && - (error === undefined || stream._readableState.autoDestroy) + (error === undefined || stream._readableState.autoDestroy || stream.destroyed) ) { destroyImpl.destroyer(stream, null); } else { diff --git a/test/parallel/test-stream-readable-async-iterators.js b/test/parallel/test-stream-readable-async-iterators.js index fb4b052bf288..63cfd22ff1b0 100644 --- a/test/parallel/test-stream-readable-async-iterators.js +++ b/test/parallel/test-stream-readable-async-iterators.js @@ -631,6 +631,29 @@ async function tests() { assert.strictEqual(r.destroyed, true); } + { + // An already destroyed stream with autoDestroy: false and an async _destroy + // must not emit an unhandled 'error' event after the iterator finishes. + // Refs: https://github.com/nodejs/node/issues/67418 + + const stream = new Readable({ + read() {}, + autoDestroy: false, + destroy(err, cb) { + setTimeout(() => cb(err), 10); + }, + }); + + const expectedErr = new Error('stream error'); + stream.destroy(expectedErr); + + await assert.rejects(async () => { + for await (const chunk of stream) { + assert.fail(`unexpected chunk: ${chunk}`); + } + }, expectedErr); + } + { // Don't destroy before 'end'.