The short answer

#

A stream moves data through your program in small chunks instead of loading it all at once. To connect streams, use pipeline() from node:stream/promises. It passes data from one stream to the next, slows the source down when the destination is busy, and destroys every stream if any of them fails.


_11
import { createReadStream, createWriteStream } from "node:fs";
_11
import { createGzip } from "node:zlib";
_11
import { pipeline } from "node:stream/promises";
_11
_11
await pipeline(
_11
createReadStream("access.log"),
_11
createGzip(),
_11
createWriteStream("access.log.gz"),
_11
);
_11
_11
console.log("Compressed");

Why it happens

#

Reading a file with readFile puts the whole thing in memory. That is fine for a config file, but a 4 GB log or a large upload can exhaust the heap or block the process for a long time. Streams solve this by handling one chunk (usually 64 KB for files) at a time.

Node has four kinds of stream:

  • Readable: a source, such as fs.createReadStream or an incoming HTTP request.
  • Writable: a destination, such as fs.createWriteStream or an HTTP response.
  • Duplex: both at once, such as a TCP socket.
  • Transform: a duplex that changes data as it passes through, such as zlib.createGzip.

The older way to connect them is .pipe(). It handles backpressure, but it does not forward errors. If the destination fails, the source keeps its file handle open, and an error on any stream without its own listener can crash the process. pipeline() was added to fix exactly that.

How to fix it

#

Use pipeline with async/await

The promise version is the most convenient. Wrap it in try and catch to handle failures from any stage.


_10
import { pipeline } from "node:stream/promises";
_10
import { createReadStream, createWriteStream } from "node:fs";
_10
_10
try {
_10
await pipeline(createReadStream("in.csv"), createWriteStream("out.csv"));
_10
} catch (error) {
_10
console.error("Copy failed:", error);
_10
}

If one stream errors, pipeline destroys the others, so file descriptors and sockets are released.

Transform data with an async generator

You do not need to subclass Transform. A pipeline stage can be an async generator function that receives the previous stream as an async iterable.


_12
import { pipeline } from "node:stream/promises";
_12
import { createReadStream, createWriteStream } from "node:fs";
_12
_12
await pipeline(
_12
createReadStream("names.txt", { encoding: "utf8" }),
_12
async function* (source) {
_12
for await (const chunk of source) {
_12
yield chunk.toUpperCase();
_12
}
_12
},
_12
createWriteStream("names-upper.txt"),
_12
);

Chunks are not lines. If you need to work line by line, use node:readline with createInterface on the read stream.

Stream a file in an HTTP response

Sending a large file without streaming buffers it all first. With pipeline, the response is written as the file is read, and a client that disconnects early stops the read.


_12
import { createServer } from "node:http";
_12
import { createReadStream } from "node:fs";
_12
import { pipeline } from "node:stream/promises";
_12
_12
createServer(async (req, res) => {
_12
res.setHeader("Content-Type", "video/mp4");
_12
try {
_12
await pipeline(createReadStream("intro.mp4"), res);
_12
} catch (error) {
_12
if (error.code !== "ERR_STREAM_PREMATURE_CLOSE") console.error(error);
_12
}
_12
}).listen(3000);

Read a stream with for await

When you only want to consume data, readable streams are async iterables.


_10
import { createReadStream } from "node:fs";
_10
_10
let bytes = 0;
_10
for await (const chunk of createReadStream("big.bin")) {
_10
bytes += chunk.length;
_10
}
_10
console.log(bytes);

Cancel a pipeline

Pass an AbortSignal as the last argument to stop it, for example after a timeout.


_10
await pipeline(source, destination, { signal: AbortSignal.timeout(10_000) });

Common pitfalls

#
  • Using .pipe() without error handling. Prefer pipeline() everywhere. If you must use .pipe(), add an error listener to every stream.
  • Ignoring backpressure in manual writes. If you call write() yourself, check its return value and wait for the drain event when it returns false. pipeline does this for you.
  • Collecting chunks into an array. Pushing every chunk into memory defeats the point. Process each chunk and move on.
  • Mixing up the two imports. pipeline from node:stream takes a callback; the one from node:stream/promises returns a promise.
  • Splitting multi-byte characters. Set encoding: "utf8" on the read stream so characters are not cut in half between chunks.
#

quick question

Was this resource helpful?