Skip to content

Commit

Permalink
stream: never flatten on toArray
Browse files Browse the repository at this point in the history
PR-URL: nodejs/node#41615
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Robert Nagy <[email protected]>
Reviewed-By: Antoine du Hamel <[email protected]>
  • Loading branch information
benjamingr authored and guangwong committed Oct 10, 2022
1 parent 0defa8d commit 31b562d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 14 deletions.
8 changes: 3 additions & 5 deletions doc/api/stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -1851,12 +1851,10 @@ added: v16.15.0
* `options` {Object}
* `signal` {AbortSignal} allows cancelling the toArray operation if the
signal is aborted.
* Returns: {Promise} a promise containing an array (if the stream is in
object mode) or Buffer with the contents of the stream.
* Returns: {Promise} a promise containing an array with the contents of the
stream.

This method allows easily obtaining the contents of a stream. If the
stream is in [object mode][object-mode] an array of its contents is returned.
If the stream is not in object mode a Buffer containing its data is returned.
This method allows easily obtaining the contents of a stream.

As this method reads the entire stream into memory, it negates the benefits of
streams. It's intended for interoperability and convenience, not as the primary
Expand Down
4 changes: 0 additions & 4 deletions lib/internal/streams/operators.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict';

const { AbortController } = require('internal/abort_controller');
const { Buffer } = require('buffer');

const {
codes: {
Expand Down Expand Up @@ -291,9 +290,6 @@ async function toArray(options) {
}
ArrayPrototypePush(result, val);
}
if (!this.readableObjectMode) {
return Buffer.concat(result);
}
return result;
}

Expand Down
12 changes: 7 additions & 5 deletions test/parallel/test-stream-toArray.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,16 @@ const assert = require('assert');
}

{
// Works on a non-object-mode stream and flattens it
// Works on a non-object-mode stream
(async () => {
const firstBuffer = Buffer.from([1, 2, 3]);
const secondBuffer = Buffer.from([4, 5, 6]);
const stream = Readable.from(
[Buffer.from([1, 2, 3]), Buffer.from([4, 5, 6])]
, { objectMode: false });
[firstBuffer, secondBuffer],
{ objectMode: false });
const result = await stream.toArray();
assert.strictEqual(Buffer.isBuffer(result), true);
assert.deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5, 6]);
assert.strictEqual(Array.isArray(result), true);
assert.deepStrictEqual(result, [firstBuffer, secondBuffer]);
})().then(common.mustCall());
}

Expand Down

0 comments on commit 31b562d

Please sign in to comment.