import { arrayBuffer } from 'node:stream/consumers';
import { Readable } from 'node:stream';
import { TextEncoder } from 'node:util';
const encoder = new TextEncoder();
const dataArray = encoder.encode('hello world from consumers!');
const readable = Readable.from(dataArray);
const data = await arrayBuffer(readable);
console.log(`from readable: ${data.byteLength}`);
// Prints: from readable: 76
Node.js module
stream/consumers
The 'node:stream/consumers' submodule offers helper functions that consume Readable streams into other forms, such as blob, arrayBuffer, text, or json.
It simplifies common stream-to-data conversions without manual event handling.
- @returns
Fulfills with an
ArrayBuffercontaining the full contents of the stream. import { blob } from 'node:stream/consumers'; const dataBlob = new Blob(['hello world from consumers!']); const readable = dataBlob.stream(); const data = await blob(readable); console.log(`from readable: ${data.size}`); // Prints: from readable: 27@returnsFulfills with a
Blobcontaining the full contents of the stream.- ): Promise<NonSharedBuffer>;
import { buffer } from 'node:stream/consumers'; import { Readable } from 'node:stream'; import { Buffer } from 'node:buffer'; const dataBuffer = Buffer.from('hello world from consumers!'); const readable = Readable.from(dataBuffer); const data = await buffer(readable); console.log(`from readable: ${data.length}`); // Prints: from readable: 27@returnsFulfills with a
Buffercontaining the full contents of the stream. - ): Promise<NonSharedUint8Array>;
import { bytes } from 'node:stream/consumers'; import { Readable } from 'node:stream'; import { Buffer } from 'node:buffer'; const dataBuffer = Buffer.from('hello world from consumers!'); const readable = Readable.from(dataBuffer); const data = await bytes(readable); console.log(`from readable: ${data.length}`); // Prints: from readable: 27@returnsFulfills with a
Uint8Arraycontaining the full contents of the stream. - ): Promise<unknown>;
import { json } from 'node:stream/consumers'; import { Readable } from 'node:stream'; const items = Array.from( { length: 100, }, () => ({ message: 'hello world from consumers!', }), ); const readable = Readable.from(JSON.stringify(items)); const data = await json(readable); console.log(`from readable: ${data.length}`); // Prints: from readable: 100@returnsFulfills with the contents of the stream parsed as a UTF-8 encoded string that is then passed through
JSON.parse(). - ): Promise<string>;
import { text } from 'node:stream/consumers'; import { Readable } from 'node:stream'; const readable = Readable.from('Hello world from consumers!'); const data = await text(readable); console.log(`from readable: ${data.length}`); // Prints: from readable: 27@returnsFulfills with the contents of the stream parsed as a UTF-8 encoded string.