Transform streams and pipeline

Intermediate · 12 min

Chain streams with stream.pipeline, write Transform streams and async generators, compress with zlib, and get errors and cleanup right.

Before thisWhy streams, and Readable and Writable basics

Software Developer Diaries · 12 min

Transform streams and pipeline

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Software Developer DiariesReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A Transform is a stream that reads input chunks and writes computed output chunks. `zlib.createGzip()`, `crypto.createHash()` and a hand-written uppercaser are all Transforms.
  • `readable.pipe(writable)` forwards data and backpressure, but it does not forward errors. If one stream fails, the others are left open and leak.
  • `pipeline()` from `node:stream/promises` connects any number of streams, destroys all of them if any one fails, and returns a promise you can `await` and `try`/`catch`.
  • An async generator function can sit in the middle of a `pipeline` as a transform step. `async function* (source) { for await (const c of source) yield f(c); }` is often simpler than subclassing `Transform`.
  • Chunk boundaries are arbitrary. A Transform that needs whole lines or records must buffer partial data itself, or use `readline` or a parser designed for streams.

Streams are most useful connected

One stream on its own is a tap. The payoff comes from chaining: read a file, compress it, write it somewhere else, all in constant memory. The unit that does the middle work is a Transform: it receives chunks from upstream, computes something, and emits chunks downstream.

Node ships Transforms for common jobs: zlib.createGzip() and createGunzip(), crypto.createHash(), and readline for splitting by line. You write your own for the rest.

Writing a Transform

import { Transform } from 'node:stream';

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

callback(null, data) pushes data downstream and says “give me the next chunk”. Passing an Error first destroys the stream. If one input chunk should produce several outputs, call this.push(...) as many times as you need before callback().

Why .pipe() is not enough

readable.pipe(writable) is the older API, and it does the data forwarding and backpressure correctly. What it skips is failure. If the source errors, the destination is not closed. If the destination errors, the source keeps reading. Chain three streams with pipe and you need three error listeners and manual cleanup, or you leak file descriptors.

pipeline exists to fix exactly that:

import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { createGzip, createGunzip } from 'node:zlib';

await pipeline(
  createReadStream('big.txt'),
  upper,
  createGzip(),
  createWriteStream('big.txt.gz'),
);

The promise resolves when the last stream finishes. If any stream errors, pipeline destroys all of them and rejects:

try {
  await pipeline(createReadStream('nope.txt'), createGzip(), createWriteStream('x.gz'));
} catch (err) {
  console.log(err.code); // ENOENT
}

There is also a callback form in node:stream, and the promise form is what you want in new code.

Generators as transform steps

You do not have to subclass anything. In pipeline, an async generator function receives the previous stage as an async iterable and yields the next stage’s chunks:

import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';

await pipeline(
  createReadStream('big.txt', 'utf8'),
  async function* (source) {
    for await (const chunk of source) yield chunk.toUpperCase();
  },
  createWriteStream('big2.txt'),
);

This form is shorter, handles backpressure through the generator protocol, and cleans up like any other stage. Reach for Transform when you need a reusable stream object or this.push flexibility, and for generators for one-off steps.

The chunk-boundary trap

Chunks are not lines. A Transform that counts or edits whole lines must handle one line arriving in two pieces. For the common case of reading lines, wrap the input in readline:

import { createInterface } from 'node:readline';

for await (const line of createInterface({ input: createReadStream('big.txt'), crlfDelay: Infinity })) {
  console.log('L:', line);
}

crlfDelay: Infinity treats \r\n as one line break even if the two characters straddle chunks. For CSV or JSON Lines, use a parser built for streaming rather than splitting strings yourself.

What the video covers

Software Developer Diaries’ video is described as covering Node.js streams, pipes, pipelines and Transforms, including Readable, Writable and Duplex streams and why chunking helps with large files. It dates from November 2022, so its exact code may use the callback pipeline or pipe. I could not read a transcript, so I can’t say which of those it favours. The error-propagation comparison with pipe, the async generator form, and the readline pitfall above are this page’s own.

Where this fits

This lesson builds on Readable and Writable basics. The remaining question is what happens when the source is faster than the destination, which is backpressure. The generator syntax is covered in iterators and generators.

Check yourself

  1. 01Why is `fs.createReadStream(a).pipe(gzip).pipe(fs.createWriteStream(b))` risky in production code?

    `pipe` does not propagate errors or destroy the other streams. If the source fails with ENOENT or the destination hits a full disk, the remaining streams stay open, file descriptors leak, and the error is only seen if you attached an `error` listener to every stream. `pipeline` handles all of that.

  2. 02How does `await pipeline(a, b, c)` report a failure partway through?

    The promise rejects with the first error, and every stream in the chain is destroyed. Reading a missing file through gzip into a file rejects with an error whose `code` is `ENOENT`, and no half-open streams remain.

  3. 03What does the callback in a Transform's `transform(chunk, encoding, callback)` do?

    It hands the processed output downstream and signals that you are ready for the next input chunk. Call `callback(null, output)` or call `this.push(output)` then `callback()`. Passing an error as the first argument destroys the stream with that error.

  4. 04You write a line-numbering Transform and it occasionally numbers half a line. Why?

    Chunks are cut at arbitrary byte positions, not at newlines, so one line can arrive split across two chunks. Keep the trailing partial line in a variable and prepend it to the next chunk, or feed the stream through `readline` first.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark