Skip to content

Commit 5367002

Browse files
KhooHaoYitbengl
authored andcommitted
stream: do cleanup when iterator is destroyed
PR-URL: #42320 Reviewed-By: Robert Nagy <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Nitzan Uziely <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 3bd0078 commit 5367002

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

lib/internal/streams/readable.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -1122,7 +1122,7 @@ async function* createAsyncIterator(stream, options) {
11221122
stream.on('readable', next);
11231123

11241124
let error;
1125-
eos(stream, { writable: false }, (err) => {
1125+
const cleanup = eos(stream, { writable: false }, (err) => {
11261126
error = err ? aggregateTwoErrors(error, err) : null;
11271127
callback();
11281128
callback = nop;
@@ -1150,6 +1150,9 @@ async function* createAsyncIterator(stream, options) {
11501150
(error === undefined || stream._readableState.autoDestroy)
11511151
) {
11521152
destroyImpl.destroyer(stream, null);
1153+
} else {
1154+
stream.off('readable', next);
1155+
cleanup();
11531156
}
11541157
}
11551158
}

test/parallel/test-stream-readable-async-iterators.js

+14
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,20 @@ async function tests() {
789789
}
790790
);
791791
}
792+
793+
// Check for dangling listeners
794+
(async function() {
795+
const readable = createReadable();
796+
const opts = { destroyOnReturn: false };
797+
while (readable.readable) {
798+
// eslint-disable-next-line no-unused-vars
799+
for await (const chunk of readable.iterator(opts)) {
800+
break;
801+
}
802+
}
803+
804+
assert.deepStrictEqual(readable.eventNames(), []);
805+
})().then(common.mustCall());
792806
}
793807

794808
{

0 commit comments

Comments
 (0)