Piping and pipeline
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()
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');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.
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:
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:
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
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:
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
import { createHash } from 'node:crypto';
const hash = createHash('sha256');
await pipeline(createReadStream('installer.iso'), hash);
console.log(hash.digest('hex')); // check a download's integritySaving a request body to disk
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:
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.
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.
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip, createGunzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';import { createReadStream, createWriteStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import { createGzip, createGunzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';
export async function gzipFile(src) {
await pipeline(createReadStream(src), createGzip(), createWriteStream(`${src}.gz`));
}
export async function gunzipFile(src) {
const out = src.replace(/\.gz$/, '');
await pipeline(createReadStream(src), createGunzip(), createWriteStream(out));
}
await gzipFile('access.log');
const [before, after] = await Promise.all([stat('access.log'), stat('access.log.gz')]);
console.log(`${before.size} → ${after.size} bytes`);Summary
pipeline(source, ...transforms, destination)connects streams and handles backpressure.- Use the promise version from
node:stream/promisesandawaitit. - If any stage fails, pipeline destroys every stream and rejects — no leaks.
.pipe()is older and doesn’t forward errors; preferpipeline.- Pipelines accept async generator functions as inline transforms.