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.
_11import { createReadStream, createWriteStream } from "node:fs";_11import { createGzip } from "node:zlib";_11import { pipeline } from "node:stream/promises";_11_11await pipeline(_11 createReadStream("access.log"),_11 createGzip(),_11 createWriteStream("access.log.gz"),_11);_11_11console.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.createReadStreamor an incoming HTTP request. - Writable: a destination, such as
fs.createWriteStreamor 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.
_10import { pipeline } from "node:stream/promises";_10import { createReadStream, createWriteStream } from "node:fs";_10_10try {_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.
_12import { pipeline } from "node:stream/promises";_12import { createReadStream, createWriteStream } from "node:fs";_12_12await 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.
_12import { createServer } from "node:http";_12import { createReadStream } from "node:fs";_12import { pipeline } from "node:stream/promises";_12_12createServer(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.
_10import { createReadStream } from "node:fs";_10_10let bytes = 0;_10for await (const chunk of createReadStream("big.bin")) {_10 bytes += chunk.length;_10}_10console.log(bytes);
Cancel a pipeline
Pass an AbortSignal as the last argument to stop it, for example after a timeout.
_10await pipeline(source, destination, { signal: AbortSignal.timeout(10_000) });
Common pitfalls
#- Using .pipe() without error handling. Prefer
pipeline()everywhere. If you must use.pipe(), add anerrorlistener to every stream. - Ignoring backpressure in manual writes. If you call
write()yourself, check its return value and wait for thedrainevent when it returnsfalse.pipelinedoes 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.
pipelinefromnode:streamtakes a callback; the one fromnode:stream/promisesreturns a promise. - Splitting multi-byte characters. Set
encoding: "utf8"on the read stream so characters are not cut in half between chunks.
Related reading
#quick question
Was this resource helpful?
by Danny