ReadableStream, WritableStream and TransformStream
Learn how the three Web Stream classes work, how to build each with its controller, and how pipeThrough and pipeTo connect them with backpressure.

The Web Streams API has three building blocks, and almost every use of it is a combination of them. A ReadableStream is a source of chunks. A WritableStream is a destination that accepts chunks. A TransformStream is both: a writable side that takes chunks in and a readable side that gives changed chunks out. You build each by passing an object of callbacks, usually start, pull or write, transform, and each callback receives a controller for talking to the stream. This post builds each class from scratch on Node.js 24 with printed output, explains how data and backpressure flow between them, shows the built-in transforms that come free (text decoding and compression) and lists the mistakes that cause stalled or leaking streams. The wider comparison with Node.js streams is in the previous post.
ReadableStream: a source
A readable stream is built from an underlying source. Its start function runs once, pull runs whenever the consumer wants more and the internal queue has room, and cancel runs if the consumer gives up. The controller offers enqueue(chunk), close() and error(reason).
let n = 0;
const numbers = new ReadableStream({
pull(controller) {
n += 1;
controller.enqueue(n);
if (n === 3) controller.close();
},
});
for await (const value of numbers) {
console.log("read", value);
}read 1
read 2
read 3pull produced one value per call, and the loop's reading is what triggered each call. A producer built on pull is lazy: if the consumer stops reading, so does the source. Using start to enqueue everything at once is simpler, and wastes memory if the source is large, because the queue grows without limit when the consumer is slow.
Reading by hand uses a reader.
const reader = new ReadableStream({
start(controller) {
controller.enqueue("a");
controller.enqueue("b");
controller.close();
},
}).getReader();
console.log(await reader.read());
console.log(await reader.read());
console.log(await reader.read());{ value: 'a', done: false }
{ value: 'b', done: false }
{ value: undefined, done: true }getReader() locks the stream, so no other reader can use it until you call reader.releaseLock(). A locked stream cannot be piped or iterated.
WritableStream: a destination
A writable stream takes an underlying sink with start, write, close and abort callbacks. write receives each chunk and may return a promise, and the stream will not call write again until that promise settles. That is how a slow sink slows the pipeline.
const received = [];
const sink = new WritableStream({
async write(chunk) {
await new Promise((resolve) => setTimeout(resolve, 5));
received.push(chunk);
},
close() {
console.log("sink closed after", received.length, "chunks");
},
});
const writer = sink.getWriter();
await writer.write("one");
await writer.write("two");
await writer.close();
console.log(received);sink closed after 2 chunks
[ 'one', 'two' ]The writer.write call returns a promise that settles when the sink has processed the chunk, so awaiting each write keeps the producer in step. Not awaiting is allowed, and the chunks queue inside the stream up to its high-water mark, with writer.ready signalling when there is room.
TransformStream: both at once
A TransformStream takes a transform(chunk, controller) function, called once per chunk, which enqueues zero or more output chunks. An optional flush(controller) runs when the input ends.
const upperCase = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
},
});
const writer = upperCase.writable.getWriter();
const reader = upperCase.readable.getReader();
writer.write("hello");
writer.close();
console.log(await reader.read());
console.log(await reader.read());{ value: 'HELLO', done: false }
{ value: undefined, done: true }A transform may emit fewer or more chunks than it receives. A line splitter is the standard example, since a chunk boundary rarely matches a line boundary, so the transform keeps the partial line in a variable and flush emits whatever is left.
function lines() {
let buffer = "";
return new TransformStream({
transform(chunk, controller) {
buffer += chunk;
const parts = buffer.split("\n");
buffer = parts.pop();
for (const line of parts) controller.enqueue(line);
},
flush(controller) {
if (buffer) controller.enqueue(buffer);
},
});
}
const source = new ReadableStream({
start(controller) {
controller.enqueue("one\ntw");
controller.enqueue("o\nthree");
controller.close();
},
});
for await (const line of source.pipeThrough(lines())) {
console.log("line:", line);
}line: one
line: two
line: threeThe word "two" was split across two chunks and reassembled. This stateful buffering is the reason transforms are written as objects with closures and not plain functions.
Connecting them: pipeThrough and pipeTo
readable.pipeThrough(transform) returns the transform's readable side, so calls chain. readable.pipeTo(writable) returns a promise that settles when the whole pipeline ends.
const out = [];
await new ReadableStream({
start(controller) {
controller.enqueue("a\nb");
controller.enqueue("\nc");
controller.close();
},
})
.pipeThrough(lines())
.pipeThrough(
new TransformStream({
transform(line, controller) {
controller.enqueue(`> ${line}`);
},
}),
)
.pipeTo(
new WritableStream({
write(line) {
out.push(line);
},
}),
);
console.log(out);[ '> a', '> b', '> c' ]The pipe handles four things for you. It moves chunks, it propagates backpressure from the sink back to the source, it forwards errors in both directions and it closes the destination when the source closes. Options such as preventClose, preventAbort and preventCancel turn off the propagation of closing and errors, and signal lets you cancel the pipe with an AbortSignal.
Backpressure in the controller
Each stream has a queue and a high-water mark, which counts chunks by default. controller.desiredSize is the high-water mark minus the queue size, and a source that checks it can stop producing.
const source = new ReadableStream(
{
start(controller) {
console.log("desiredSize at start:", controller.desiredSize);
controller.enqueue("a");
console.log("after one chunk:", controller.desiredSize);
controller.enqueue("b");
console.log("after two chunks:", controller.desiredSize);
},
},
{ highWaterMark: 2 },
);desiredSize at start: 2
after one chunk: 1
after two chunks: 0At zero the queue is at its limit, and a pull-based source will not be called again until the consumer reads. A source that ignores desiredSize and keeps enqueuing from start breaks the contract, and memory grows. Strategies can count bytes with new ByteLengthQueuingStrategy({ highWaterMark: 16384 }), which is the right choice for binary data.
Built-in transforms
Several are available as globals, and they connect with pipeThrough.
const encoded = new ReadableStream({
start(controller) {
controller.enqueue("compress me, compress me, compress me");
controller.close();
},
})
.pipeThrough(new TextEncoderStream())
.pipeThrough(new CompressionStream("gzip"))
.pipeThrough(new DecompressionStream("gzip"))
.pipeThrough(new TextDecoderStream());
const parts = [];
for await (const part of encoded) parts.push(part);
console.log(parts.join(""));compress me, compress me, compress meTextEncoderStream turns strings into Uint8Array chunks, CompressionStream and DecompressionStream handle gzip, deflate and deflate-raw, and TextDecoderStream turns bytes back into strings and takes care of multi-byte characters split across chunks, which a naive toString per chunk does not.
Mistakes that cause trouble
Forgetting to close. A ReadableStream that never calls close() never ends, and for await and pipeTo wait forever.
Locking. Reading from a stream with getReader() locks it. Piping a locked stream throws a TypeError.
Reading twice. A stream can be consumed once. To use it twice, call tee(), which splits it into two branches, and remember that a slow branch buffers data for the faster one.
Swallowing errors. If a transform throws, the stream errors and the pipeline rejects. Catch that rejection from pipeTo.
Chunk type assumptions. A byte stream yields Uint8Array chunks of arbitrary sizes, so never assume a chunk is a whole message or line.
Designing your own transform
When you write a transform, decide first what a chunk means. A transform that assumes each chunk is a complete message works in a test where you enqueue whole strings, and fails on a network where chunks arrive split at arbitrary byte boundaries. The safe design keeps whatever is incomplete in a closure variable and emits only whole units, which is what the line splitter above does.
Next, decide what to do with errors in a single chunk. Throwing from transform errors the whole stream, which is right for corrupt data you cannot recover from. If a bad record should be skipped, catch inside transform, report it through your own channel and continue with the next chunk. Finally, keep each transform small and single purpose. A pipeline of four tiny transforms is easier to test and reorder than one large one, and the cost of each extra stage is a queue and a few function calls per chunk, which is small next to the work of real input and output.
Reading a stream you did not write
When a pipeline misbehaves, the quickest way to understand it is to put a logging transform between two stages. It passes each chunk through unchanged and prints a short description, such as the chunk's type and length. Moving that stage along the pipeline shows where the chunks change shape, where they stop flowing and where they are split or merged. If nothing arrives after a certain stage, that stage never called close() or is waiting on a promise that never settles. If chunks arrive in unexpected sizes, check whether an upstream byte stream is handing you pieces that are not aligned to your records. These two symptoms, a stage that stalls and chunks that are not whole records, account for most stream bugs.


