-
Notifications
You must be signed in to change notification settings - Fork 29.8k
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 <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]> Reviewed-By: Gus Caplan <[email protected]> Reviewed-By: Beth Griggs <[email protected]>
- Loading branch information
1 parent
20f64a9
commit 894aaa2
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