stream: do not chunk strings and Buffer in Readable.from

PR-URL: https://github.com/nodejs/node/pull/30912
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
Matteo Collina authored and Beth Griggs committed 2020-02-06 02:49:29 +00:00
1 parent d19316d2d9
commit 322912aa65
3 files changed
+28 -1

No files matched your search

+4
View File
@@ -1641,6 +1641,10 @@ readable.on('data', (chunk) => {
});
```
Calling `Readable.from(string)` or `Readable.from(buffer)` will not have
the strings or buffers be iterated to match the other streams semantics
for performance reasons.
## API for Stream Implementers
<!--type=misc-->
+12
View File
@@ -4,6 +4,7 @@ const {
SymbolAsyncIterator,
SymbolIterator
} = primordials;
const { Buffer } = require('buffer');
const {
ERR_INVALID_ARG_TYPE
@@ -11,6 +12,17 @@ const {
function from(Readable, iterable, opts) {
let iterator;
if (typeof iterable === 'string' || iterable instanceof Buffer) {
return new Readable({
objectMode: true,
...opts,
read() {
this.push(iterable);
this.push(null);
}
});
}
if (iterable && iterable[SymbolAsyncIterator])
iterator = iterable[SymbolAsyncIterator]();
else if (iterable && iterable[SymbolIterator])
+12 -1
View File
@@ -56,13 +56,23 @@ async function toReadablePromises() {
async function toReadableString() {
const stream = Readable.from('abc');
const expected = ['a', 'b', 'c'];
const expected = ['abc'];
for await (const chunk of stream) {
strictEqual(chunk, expected.shift());
}
}
async function toReadableBuffer() {
const stream = Readable.from(Buffer.from('abc'));
const expected = ['abc'];
for await (const chunk of stream) {
strictEqual(chunk.toString(), expected.shift());
}
}
async function toReadableOnData() {
async function* generate() {
yield 'a';
@@ -154,6 +164,7 @@ Promise.all([
toReadableSyncIterator(),
toReadablePromises(),
toReadableString(),
toReadableBuffer(),
toReadableOnData(),
toReadableOnDataNonObject(),
destroysTheStreamWhenThrowing(),