Skip to content
jshacks.dev
Async

Streams in JavaScript: Web Streams vs Node Streams

Compare Web Streams and Node.js streams, see how to read, transform and pipe data with each, how to convert between them and which API to choose.

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

A stream is a way to process data a piece at a time instead of loading all of it first. That is the whole value: a 4 GB file can be hashed with a few kilobytes of memory, and the first byte of a response can be sent before the last is ready. JavaScript now has two stream APIs that do this. Node.js streams, in node:stream, have been there since the first versions of Node.js and power fs, http and zlib. Web Streams, the ReadableStream, WritableStream and TransformStream classes, are a web standard that browsers ship and that Node.js 24 supports globally, with fetch returning them. This post compares the two on the same tasks, shows the converters between them and says which to choose. The three Web Stream classes get a closer look in their own post.

The same job in both

The task: take text, uppercase it and collect the output.

JavaScript
import { Readable, Transform, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";

const chunks = [];

await pipeline(
  Readable.from(["hello ", "streams"]),
  new Transform({
    transform(chunk, encoding, callback) {
      callback(null, chunk.toString().toUpperCase());
    },
  }),
  new Writable({
    write(chunk, encoding, callback) {
      chunks.push(chunk.toString());
      callback();
    },
  }),
);

console.log(chunks.join(""));
Text
HELLO STREAMS

The Web Streams version:

JavaScript
const chunks = [];

await new ReadableStream({
  start(controller) {
    controller.enqueue("hello ");
    controller.enqueue("streams");
    controller.close();
  },
})
  .pipeThrough(
    new TransformStream({
      transform(chunk, controller) {
        controller.enqueue(chunk.toUpperCase());
      },
    }),
  )
  .pipeTo(
    new WritableStream({
      write(chunk) {
        chunks.push(chunk);
      },
    }),
  );

console.log(chunks.join(""));
Text
HELLO STREAMS

Both do the same work. The Node.js version uses callbacks and a pipeline helper, and the Web version uses promises, pipeThrough and pipeTo throughout. The Web version's methods return promises, so there is no callback to call.

Differences that matter

Node.js streamsWeb Streams
Where it runsNode.js onlyBrowsers, Node.js, Deno, Bun, edge runtimes
StyleEvent emitter plus callbacksPromises and async iteration
ChunksBuffer, string or objects (object mode)Any JavaScript value, Uint8Array for bytes
Backpressurewrite() returns false, then wait for drainController desiredSize and promise-based pull and write
Pipingpipeline() handles errors and cleanuppipeThrough and pipeTo
Ecosystemfs, http, zlib, crypto, child_processfetch, Response.body, Blob.stream(), CompressionStream

The ecosystem row is the practical one. If you work with files, sockets and child processes on Node.js, you get Node.js streams. If you work with fetch, service workers or code that must run in more than one environment, you get Web Streams.

Async iteration works on both

Both kinds can be read with for await, which is the simplest way to consume either.

JavaScript
import { Readable } from "node:stream";

for await (const chunk of Readable.from(["a", "b"])) {
  console.log("node chunk:", chunk);
}

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

for await (const chunk of web) {
  console.log("web chunk:", chunk);
}
Text
node chunk: a
node chunk: b
web chunk: c
web chunk: d

Async iteration of a ReadableStream works in Node.js and in current browsers, though a few older browser versions lacked it. The loop reads one chunk at a time, so a slow loop body naturally slows the producer.

Converting between them

Node.js provides converters, both directions, as static methods.

JavaScript
import { Readable, Writable } from "node:stream";

// Node -> Web
const webReadable = Readable.toWeb(Readable.from(["x", "y"]));

// Web -> Node
const nodeReadable = Readable.fromWeb(
  new ReadableStream({
    start(controller) {
      controller.enqueue(new TextEncoder().encode("hello"));
      controller.close();
    },
  }),
);

const parts = [];
for await (const chunk of webReadable) parts.push(chunk);
console.log(parts);

for await (const chunk of nodeReadable) console.log(Buffer.from(chunk).toString());
Text
[ 'x', 'y' ]
hello

There are matching Writable.toWeb, Writable.fromWeb, Duplex.toWeb and Duplex.fromWeb. The converters keep backpressure working across the boundary. The typical use is passing the body of a fetch response into a Node.js file stream.

JavaScript
import { createWriteStream } from "node:fs";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

const response = await fetch("https://example.com/file.bin");

await pipeline(Readable.fromWeb(response.body), createWriteStream("file.bin"));
console.log("saved");
Text
saved

This downloads a file without holding it in memory, assuming the URL is reachable and returns a body.

Backpressure, in one example each

Backpressure is the signal from a slow consumer to a fast producer to slow down, and without it, memory fills with queued data. Node.js streams expose it as the return value of write().

JavaScript
import { Writable } from "node:stream";

const slow = new Writable({
  highWaterMark: 4,
  write(chunk, encoding, callback) {
    setTimeout(callback, 5);
  },
});

console.log("first write ok:", slow.write("ab"));
console.log("second write ok:", slow.write("cdef"));
Text
first write ok: true
second write ok: false

After the second write, the buffered bytes exceed the highWaterMark of 4, so write() returned false, which means "stop writing until drain". Using pipeline or pipe handles this for you. Web Streams express the same idea through a queuing strategy and controller.desiredSize, which becomes zero or negative when the queue is full, and a pull function that is called only when there is room. The post on backpressure works through both.

Error handling and cleanup

Node.js streams have a long history of leaks from forgotten error handling: a piped stream that fails does not destroy the others unless you use pipeline. Always use pipeline from node:stream or node:stream/promises, and never chain .pipe() calls for anything that matters. Web Streams propagate errors through pipeTo and pipeThrough automatically, and cancel the source when the destination fails, unless you set preventCancel.

JavaScript
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

try {
  await pipeline(
    Readable.from(["ok"]),
    async function* (source) {
      for await (const chunk of source) {
        yield chunk;
        throw new Error("transform failed");
      }
    },
    async function (source) {
      for await (const chunk of source) console.log("sink got", chunk);
    },
  );
} catch (error) {
  console.log("pipeline rejected:", error.message);
}
Text
sink got ok
pipeline rejected: transform failed

Note that pipeline accepts async generator functions as transforms and sinks, which is often easier to write than a Transform subclass.

Which should you choose

Use Web Streams for new code that touches fetch, runs on the edge, in the browser or in a library intended for several runtimes, or when you want promise-based code without callbacks. Use Node.js streams when you are working with fs, net, http servers, child_process, zlib or the many packages built on them, and when you need object mode or fine control over buffering. In practice you will use both in the same program and convert at the boundary.

One quirk deserves a warning: Web Streams use Uint8Array for bytes, while Node.js streams use Buffer, which is a subclass of Uint8Array. Moving data across usually works as is, but code that calls Buffer methods on a chunk from a Web Stream will fail, so wrap it with Buffer.from(chunk).

Practical advice for mixed code bases

In a typical Node.js service you will have both kinds of stream in the same file. An HTTP handler may receive a Node.js IncomingMessage, call fetch to reach another service and get a Web Stream back, then pipe the result into the response. Keep the conversion at the edges, in one or two helper functions, and keep the logic in between written against a single style. Async generators work well as that middle layer, because they accept either kind of stream through for await and produce a plain async iterable that either kind of consumer can turn back into a stream with Readable.from or ReadableStream.from where available.

When a library hands you a stream, check which kind it is before you write code against it. The method names give it away: on("data"), pipe and pause belong to Node.js streams, while getReader, pipeThrough and tee belong to Web Streams. Mixing them up produces errors like "pipe is not a function" that waste time. And when you design a new package that must run in several environments, expose Web Streams, since a Node.js consumer can convert them in one line and a browser consumer cannot convert anything the other way.

Also inNode.js
Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.