Skip to content
jshacks.dev
Async

Node Streams vs Web Streams and How to Convert Them

Compare Node.js streams and web streams on API, backpressure, async iteration and portability, and convert between them with Readable.fromWeb and toWeb.

7 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the Node.js, JavaScript, Vite, TypeScript and npm logos.

Node.js has two stream systems, and in Node.js 24 you will meet both in the same program. The older one is in node:stream: Readable, Writable, Transform, and the pipeline helper. The newer one is the WHATWG web streams standard: ReadableStream, WritableStream and TransformStream, the same classes browsers expose and the type that fetch returns as response.body. They model the same idea, data moving in chunks with backpressure, but their APIs, defaults and chunk types differ. This post compares node streams vs web streams on five points, shows how to convert between them with Readable.fromWeb() and Readable.toWeb(), and says which to prefer for new code. All output below comes from short programs whose behavior is deterministic.

Same idea, different surface

A Node.js Readable is an event emitter with a pull-and-push buffer: it emits data events, or you iterate it with for await. A web ReadableStream is built around a reader and a controller: you read through stream.getReader(), or iterate it directly, which Node.js supports.

read-both.mjsJavaScript
import { Readable } from "node:stream";

const nodeStream = Readable.from(["a", "b", "c"]);
const webStream = new ReadableStream({
  start(controller) {
    for (const piece of ["a", "b", "c"]) controller.enqueue(piece);
    controller.close();
  },
});

const fromNode = [];
for await (const chunk of nodeStream) fromNode.push(chunk);

const fromWeb = [];
for await (const chunk of webStream) fromWeb.push(chunk);

console.log(fromNode, fromWeb);
Text
[ 'a', 'b', 'c' ] [ 'a', 'b', 'c' ]

Both are consumed with for await, which hides most of the difference for a simple read. The differences show up when you write a source or a transform.

Writing a source

A Node.js stream is usually a class with a _read method, or created with Readable.from() over an iterable. A web stream takes an underlying source object with start, pull and cancel methods.

sources.mjsJavaScript
import { Readable } from "node:stream";

// Node: from an async generator
const nodeSource = Readable.from(
  (async function* () {
    yield "one";
    yield "two";
  })()
);

// Web: a pull-based source that counts to three
let n = 0;
const webSource = new ReadableStream({
  pull(controller) {
    n++;
    controller.enqueue(`chunk ${n}`);
    if (n === 3) controller.close();
  },
});

const out = [];
for await (const piece of nodeSource) out.push(piece);
for await (const piece of webSource) out.push(piece);
console.log(out);
Text
[ 'one', 'two', 'chunk 1', 'chunk 2', 'chunk 3' ]

The web pull method is called whenever the internal queue has room, which is how backpressure is expressed: the stream only asks for more when the consumer has taken what it had. Node.js streams express the same thing through highWaterMark and the return value of write().

Chunk types

Node.js streams default to Buffer or string chunks, and switch to arbitrary values only with objectMode: true. Web streams accept any JavaScript value as a chunk and have no such mode, but byte streams for binary data use Uint8Array. When you mix them, the chunk type is the first thing to check. A web stream from fetch produces Uint8Array chunks, while a Node.js Readable from fs.createReadStream() produces Buffer, which is a subclass of Uint8Array, so code that handles one usually handles the other.

Transforms and pipelines

A transform in each system takes input and produces output. In Node.js you write a Transform with a transform(chunk, encoding, callback) method, or pass an async generator function to pipeline. In web streams you use TransformStream, with a transform(chunk, controller) method that calls controller.enqueue().

transforms.mjsJavaScript
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";

const upperNode = new Transform({
  transform(chunk, encoding, callback) {
    callback(null, chunk.toString().toUpperCase());
  },
});

const upperWeb = new TransformStream({
  transform(chunk, controller) {
    controller.enqueue(chunk.toUpperCase());
  },
});

const results = [];
await pipeline(Readable.from(["ab", "cd"]), upperNode, async function (source) {
  for await (const chunk of source) results.push(chunk.toString());
});

const web = new ReadableStream({
  start(c) {
    c.enqueue("ef");
    c.enqueue("gh");
    c.close();
  },
}).pipeThrough(upperWeb);
for await (const chunk of web) results.push(chunk);

console.log(results);
Text
[ 'AB', 'CD', 'EF', 'GH' ]

The shapes differ in how composition works. Node.js has pipeline, which wires any number of stages, destroys all of them on error and returns a promise. Web streams compose with pipeThrough() and pipeTo(), which also propagate errors and cancellation. Node.js streams also have a long tail of conveniences such as Readable.prototype.map, filter and toArray, which are documented as experimental helpers, so check the stability note for your Node.js release before using them in production.

Converting between the two

Node.js includes converters on Readable, Writable and Duplex: fromWeb() takes a web stream and returns the Node.js equivalent, and toWeb() does the reverse.

convert.mjsJavaScript
import { Readable } from "node:stream";

const web = new ReadableStream({
  start(controller) {
    controller.enqueue("x");
    controller.enqueue("y");
    controller.close();
  },
});

const asNode = Readable.fromWeb(web, { objectMode: true });
const first = [];
for await (const chunk of asNode) first.push(chunk);
console.log("web to node:", first);

const node = Readable.from(["p", "q"]);
const asWeb = Readable.toWeb(node);
const second = [];
for await (const chunk of asWeb) second.push(chunk);
console.log("node to web:", second);
Text
web to node: [ 'x', 'y' ]
node to web: [ 'p', 'q' ]

The objectMode: true option matters in the first conversion, because our chunks are strings and a non-object-mode stream expects buffers or strings with an encoding. Converting a binary web stream, such as response.body, needs no option. The stream converters are marked as experimental in some Node.js documentation versions, so read the page for your release before relying on edge cases such as destroy semantics.

Where each wins

Web streams are the portable choice. The same code runs in browsers, in Deno, in Bun and in Cloudflare Workers, and fetch already hands you one. If you write a library that processes data and wants to run everywhere, accept and return web streams.

Node.js streams win on ecosystem and server features. Sockets, fs, zlib, child_process and HTTP servers in Node.js all expose the older streams, and pipeline is a mature tool for wiring them with correct cleanup. Some performance-sensitive paths in Node.js are tuned for them. Libraries for compression, parsing and databases still target them first.

QuestionNode.js streamsWeb streams
Runs in the browserNoYes
Core modules (fs, net, zlib)NativeVia conversion or newer APIs
fetch response bodyConvertNative
CompositionpipelinepipeThrough, pipeTo
Object chunksobjectModeAny value
Cancellationdestroy()cancel() and AbortSignal

A good rule is to use whichever the surrounding code uses and convert at the boundary. A server that reads files with fs.createReadStream() and sends them through pipeline stays in Node.js streams. A function that processes fetch results stays in web streams.

Mistakes at the boundary

Three mistakes recur. First, converting repeatedly in a loop, which adds layers of buffering. Convert once at the edge. Second, forgetting that a web stream can be read only once and is locked while a reader holds it: calling getReader() twice throws, and a stream you started iterating cannot also be piped. Use stream.tee() to split one stream into two branches, remembering that the branches buffer data for the slower consumer. Third, ignoring errors from conversion. A destroyed Node.js stream becomes a cancelled web stream and the reverse, so handle errors on the side that does the final consuming.

Where the advice stops

Do not rewrite a working Node.js pipeline into web streams just for the standard. The gain is portability, and a server-only service does not need it. Conversely, do not wrap everything in Node.js streams if the code also runs at an edge platform where node:stream is unavailable.

Backpressure in each model

Backpressure is the reason streams exist, so it is worth seeing how each side expresses it. A Node.js Writable returns false from write() when its internal buffer passes highWaterMark, and the producer is expected to stop until the drain event fires. pipeline and pipe do that for you, which is the main reason to use them instead of calling write() in a loop. A web WritableStream exposes the same signal through writer.ready, a promise that resolves when the sink can take more, and writer.desiredSize, a number that goes to zero or below when the queue is full.

The two systems also differ in how much they buffer by default. Node.js streams in byte mode buffer about 16 KiB before signaling, and object mode streams count 16 objects. Web streams count chunks by default, with a high water mark of one chunk unless you pass a queuing strategy, such as new CountQueuingStrategy({ highWaterMark: 8 }) or ByteLengthQueuingStrategy. If a pipeline is slow because every stage waits on a one-chunk buffer, a larger strategy on the fast side can smooth it, at the cost of memory. Decide the numbers from the size of your chunks, not from a guess, and remember that the buffer lives in every stage, so a long pipeline multiplies it.

Also inNode.js
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.