Node.js

Consume a Web ReadableStream in Node.js

A Web ReadableStream can provide chunks through async iteration in Node.js. Decode byte chunks with a streaming decoder when character sequences can cross chunk boundaries.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const encoder = new TextEncoder();
const stream = new ReadableStream({
  start(controller) {
    controller.enqueue(encoder.encode("hello "));
    controller.enqueue(encoder.encode("world"));
    controller.close();
  }
});
let text = "";
for await (const chunk of stream.pipeThrough(new TextDecoderStream())) text += chunk;
console.log(text);

How it works

TextDecoderStream transforms byte chunks into text while retaining incomplete encoded sequences between chunks. This is different from decoding each arbitrary chunk as an independent string. The tiny example collects the final result only for display.

Limits and mistakes

Web streams and classic Node streams are different interfaces, although adapters exist. A stream can be locked by one reader, and cancellation behavior matters if consumption stops early. Avoid retaining the whole body when the real input is large.

Check the result

Expect hello world. Split a multibyte UTF-8 character across byte chunks in another fixture to confirm decoding does not introduce replacement characters.

Sources

Reference documentation for the behavior used in this guide: