-
Notifications
You must be signed in to change notification settings - Fork 30k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
stream: extract Readable.from in its own file
See: nodejs/readable-stream#420 PR-URL: #30140 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: Gus Caplan <me@gus.host> Reviewed-By: Beth Griggs <Bethany.Griggs@uk.ibm.com>
- Loading branch information
1 parent
8e0ea6d
commit c4dc53c
Showing
3 changed files
with
51 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
'use strict'; | ||
|
||
const { | ||
ERR_INVALID_ARG_TYPE | ||
} = require('internal/errors').codes; | ||
|
||
function from(Readable, iterable, opts) { | ||
let iterator; | ||
if (iterable && iterable[Symbol.asyncIterator]) | ||
iterator = iterable[Symbol.asyncIterator](); | ||
else if (iterable && iterable[Symbol.iterator]) | ||
iterator = iterable[Symbol.iterator](); | ||
else | ||
throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); | ||
|
||
const readable = new Readable({ | ||
objectMode: true, | ||
...opts | ||
}); | ||
// Reading boolean to protect against _read | ||
// being called before last iteration completion. | ||
let reading = false; | ||
readable._read = function() { | ||
if (!reading) { | ||
reading = true; | ||
next(); | ||
} | ||
}; | ||
async function next() { | ||
try { | ||
const { value, done } = await iterator.next(); | ||
if (done) { | ||
readable.push(null); | ||
} else if (readable.push(await value)) { | ||
next(); | ||
} else { | ||
reading = false; | ||
} | ||
} catch (err) { | ||
readable.destroy(err); | ||
} | ||
} | ||
return readable; | ||
} | ||
|
||
module.exports = from; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters