stream: close iterator in Readable.from

Call iterator.return() if not all of its values are consumed.

Fixes: https://github.com/nodejs/node/issues/32842

PR-URL: https://github.com/nodejs/node/pull/32844
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Zeyu Yang <himself65@outlook.com>
This commit is contained in:
Vadzim Zieńka authored and Michaël Zasso committed 2020-05-13 17:52:54 +02:00
1 parent 698e21b346
commit 5df8ab16f2
2 files changed
+229 -1

No files matched your search

+31 -1
View File
@@ -34,21 +34,51 @@ function from(Readable, iterable, opts) {
objectMode: true,
...opts
});
// Reading boolean to protect against _read
// being called before last iteration completion.
let reading = false;
// needToClose boolean if iterator needs to be explicitly closed
let needToClose = false;
readable._read = function() {
if (!reading) {
reading = true;
next();
}
};
readable._destroy = function(error, cb) {
if (needToClose) {
needToClose = false;
close().then(
() => process.nextTick(cb, error),
(e) => process.nextTick(cb, error || e),
);
} else {
cb(error);
}
};
async function close() {
if (typeof iterator.return === 'function') {
const { value } = await iterator.return();
await value;
}
}
async function next() {
try {
needToClose = false;
const { value, done } = await iterator.next();
needToClose = !done;
const resolved = await value;
if (done) {
readable.push(null);
} else if (readable.push(await value)) {
} else if (readable.destroyed) {
await close();
} else if (readable.push(resolved)) {
next();
} else {
reading = false;