Node.js Reference ยท Streams and readline
The Node.js stream/consumers module
Reference for node:stream/consumers: read a whole stream into text, JSON, a Buffer, an ArrayBuffer or a Blob with one awaited call, plus memory caveats.
node:stream/consumers has five small functions that read an entire stream and give you the result in one form: text(), json(), buffer(), arrayBuffer() and blob(). They save you from writing the same "collect the chunks, then decode" loop every time you want the full contents of a request, a child process output or a file.
Each function accepts a Node.js Readable, a web ReadableStream or any async iterable of chunks, and returns a promise. Chunks may be strings, Buffers or Uint8Arrays; text() decodes bytes as UTF-8.
import { text, json } from 'node:stream/consumers'; const body = await text(readable); const data = await json(readable); // use one consumer per stream
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
import { text, json, buffer, arrayBuffer, blob } from 'node:stream/consumers'; text(stream): Promise<string> json(stream): Promise<any> buffer(stream): Promise<Buffer> arrayBuffer(stream): Promise<ArrayBuffer> blob(stream): Promise<Blob>
| Name | Description |
|---|---|
stream |
A Readable, a web ReadableStream, or an async iterable of strings, Buffers or typed arrays. |
Returns: a promise for the whole content. text() yields a string, json() the parsed value, buffer() a Buffer, arrayBuffer() an ArrayBuffer and blob() a Blob.
Errors: json() rejects with a SyntaxError for invalid JSON. Any error emitted by the stream rejects the promise. A stream that is already consumed yields empty content.
Usage notes
- Everything is held in memory. These functions have no size limit. Never call them on untrusted input without capping the size, for example by counting bytes in a
Transformfirst. - Use one consumer per stream. After the first read the stream has ended; a second consumer sees nothing.
- Strings from object-mode streams. If a stream emits strings,
text()concatenates them; if it emits other objects, the call fails with a type error. json()isJSON.parse(await text()). Empty input is aSyntaxError, notnull.- Handy for child processes.
await text(child.stdout)collects the output of a spawned process without manual listeners. - Same names as
Response. The methods mirrorresponse.text(),response.json()andresponse.blob(), so code that readsfetch()bodies translates directly. - Added in Node.js 16.7.