Node.js Reference ยท Streams and readline
Node.js readable.toArray() method
Reference for readable.toArray() in Node.js: read a whole stream into an array, limit memory with signals and operators, and avoid it on large streams.
readable.toArray([options]) reads a stream to the end and returns a promise for an array of all its chunks. It is handy for small streams, tests, and for the tail of an operator chain such as filter().map().toArray().
Everything is held in memory, so it is the wrong tool for large or endless streams. Combine it with take() to bound the result.
const chunks = await readable.toArray();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
readable.toArray([options]): Promise<any[]>
| Name | Description |
|---|---|
options.signal |
An AbortSignal. If it aborts, the promise rejects with an AbortError. |
Returns: a promise for an array with one entry per chunk, in order.
Errors: the promise rejects if the stream emits an error or is destroyed before ending.
Usage notes
- The array holds chunks, not bytes. A byte stream may split data at arbitrary points, so use
Buffer.concat(chunks)(orsetEncoding()plusjoin("")) for the full content. - Memory grows with the stream. For files of unknown size, process chunks incrementally with async iteration instead.
- After
toArray(), the stream is finished and destroyed. It cannot be read again. - On an endless source it never resolves; use
take(n)first. - Compared with
for await,toArray()is shorter but gives no chance to react to chunks while they arrive. - It lives in the same family as
map(),filter(),reduce(), which are described on one page.