Piping and pipeline

Topic 2 of 3 in Streams6 min readIntermediateFree course

Overview

Streams become really powerful when you connect them: read a file → compress it → encrypt it → upload it, with only a few chunks in memory at any time. Each stage works on its own chunk while the next stage works on the previous one, like an assembly line.

Node gives you two ways to connect streams: the older .pipe() method and the modern pipeline() function. This topic shows why you should almost always use pipeline().

pipeline()

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

await pipeline(
  createReadStream('access.log'),
  createGzip(),
  createWriteStream('access.log.gz'),
);
console.log('Compressed');

A pipeline of three streams: createReadStream reading access.log, createGzip compressing, and createWriteStream writing access.log.gz. Chunks of 64 KB flow left to right, with only a few in memory at once. await pipeline(read, gzip, write) rejects if any stage fails.

pipeline takes a source, any number of transforms, and a destination. It:

  • connects them in order,
  • handles backpressure — a slow destination automatically slows the source,
  • handles errors — if any stage fails, every stream is destroyed (files closed, sockets released) and the promise rejects,
  • resolves when the destination has finished.
JavaScript
try {
  await pipeline(createReadStream('missing.log'), createGzip(), createWriteStream('out.gz'));
} catch (err) {
  console.error('Compression failed:', err.code); // ENOENT — and nothing is left open
}

Why not .pipe()?

You’ll see .pipe() in older tutorials:

JavaScript
createReadStream('access.log')
  .pipe(createGzip())
  .pipe(createWriteStream('access.log.gz'));

It looks neat, and it handles backpressure. But it has a serious flaw: errors are not forwarded. If the read stream fails, the gzip and write streams are left open — leaking file descriptors and memory — and unless you add an 'error' listener to every stream, the error crashes your process. pipeline() fixes all of that, so prefer it everywhere.

Inline transforms with generators

Between the source and destination, you can pass an async generator function. It receives the previous stage as an async iterable and yields new chunks — the easiest way to write a custom processing step:

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

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

The generator can also filter (yield nothing for some chunks), count, or call other async functions. Because pipeline waits for the generator, backpressure still works.

Real-world pipelines

Serving a compressed download

JavaScript
import { createGzip } from 'node:zlib';

app.get('/logs/today', async (req, res) => {
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.setHeader('Content-Encoding', 'gzip');
  await pipeline(createReadStream('logs/today.log'), createGzip(), res);
});

The browser decompresses automatically because of the Content-Encoding header.

Downloading a file from the web to disk

fetch returns a web stream; Readable.fromWeb converts it to a Node stream:

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

const res = await fetch('https://example.com/dataset.csv');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await pipeline(Readable.fromWeb(res.body), createWriteStream('dataset.csv'));

A 2 GB download uses the same small amount of memory as a 2 KB one.

Hashing a large file

JavaScript
import { createHash } from 'node:crypto';

const hash = createHash('sha256');
await pipeline(createReadStream('installer.iso'), hash);
console.log(hash.digest('hex')); // check a download's integrity

Saving a request body to disk

JavaScript
app.put('/files/:name', async (req, res) => {
  const target = resolveUpload(req.params.name); // from Paths and URLs — never trust raw input!
  await pipeline(req, createWriteStream(target));
  res.status(201).end();
});

Cancelling a pipeline

Pass an AbortSignal to stop a long pipeline — for example, when the user cancels or a time limit is reached:

JavaScript
const ac = new AbortController();
setTimeout(() => ac.abort(), 30_000);

try {
  await pipeline(source, transform, destination, { signal: ac.signal });
} catch (err) {
  if (err.name === 'AbortError') console.log('Export cancelled');
  else throw err;
}

Web streams

Browsers have their own stream API (ReadableStream, WritableStream, TransformStream), and Node supports it too — fetch uses it. The ideas are the same. When you need to cross between the two worlds, use Readable.fromWeb() / Readable.toWeb() and Writable.fromWeb() / Writable.toWeb().

Rule of thumb: if you’re connecting streams, write await pipeline(…). It’s correct by default — backpressure, errors and clean-up included.

Exercise

Compress and decompress

Write gzipFile(src) that compresses a file to src + '.gz', and gunzipFile(src) that restores it. Use pipeline from node:stream/promises. Then compare the file sizes.

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

Summary

  • pipeline(source, ...transforms, destination) connects streams and handles backpressure.
  • Use the promise version from node:stream/promises and await it.
  • If any stage fails, pipeline destroys every stream and rejects — no leaks.
  • .pipe() is older and doesn’t forward errors; prefer pipeline.
  • Pipelines accept async generator functions as inline transforms.