stream.pipeline and Error Handling in Node.js 24
Learn why pipe leaks resources on errors and how stream.pipeline in Node.js 24 destroys every stream, rejects once and supports AbortSignal and generators.

readable.pipe(writable) looks like the whole job: data flows from one to the other with backpressure handled. What it does not do is handle failure. If the readable errors, the writable is left open, waiting for an end that never comes. If the writable errors, the readable is left paused and holding a file descriptor. Neither error reaches a single place where you can catch it, so a failing upload leaks a handle per attempt until the process runs out. stream.pipeline fixes all of that in one call. This post compares the two with exact output for Node.js 24, shows the promise form from node:stream/promises, covers AbortSignal and async generator stages and lists the corners where you still have to think.
The problem with pipe
import { Readable, Writable } from "node:stream";
const source = new Readable({
read() {
this.destroy(new Error("source failed"));
},
});
const sink = new Writable({
write(chunk, encoding, callback) {
callback();
},
});
source.on("error", (error) => console.log("source error:", error.message));
source.pipe(sink);
setImmediate(() => {
console.log("sink destroyed:", sink.destroyed);
});source error: source failed
sink destroyed: falseThe source failed and was destroyed, but pipe did nothing to the sink. It stays open. With a file as the sink, the descriptor stays open as well, until the garbage collector eventually closes it or the process exits. You also needed an error listener on the source, or the process would have crashed on an unhandled error event. Each stream in the chain needs its own, and you must remember to destroy the others yourself.
The same chain with pipeline
import { Readable, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
const source = new Readable({
read() {
this.destroy(new Error("source failed"));
},
});
const sink = new Writable({
write(chunk, encoding, callback) {
callback();
},
});
try {
await pipeline(source, sink);
} catch (error) {
console.log("pipeline rejected:", error.message);
}
console.log("sink destroyed:", sink.destroyed);pipeline rejected: source failed
sink destroyed: trueOne rejection, from one place, and every stream is destroyed. That is the contract: when any stream in the chain errors or closes early, pipeline destroys all the others and reports the first error. The promise resolves only when the last stream has finished writing.
The callback version
stream.pipeline also has a callback form, from the main node:stream module, which is useful when you are not in async code.
import { Readable, Writable, pipeline } from "node:stream";
const received = [];
pipeline(
Readable.from(["a", "b", "c"]),
new Writable({
objectMode: true,
write(chunk, encoding, callback) {
received.push(chunk);
callback();
},
}),
(error) => {
console.log(error ? `failed: ${error.message}` : "done", received);
}
);done [ 'a', 'b', 'c' ]The callback receives the first error or nothing. It is called exactly once, which is the other thing pipe cannot promise.
Transforms in the middle
Any number of transforms can sit between source and sink, and an error in any stage tears down the whole chain.
import { Readable, Transform, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
const upper = new Transform({
objectMode: true,
transform(chunk, encoding, callback) {
if (chunk === "bad") return callback(new Error("bad chunk"));
callback(null, chunk.toUpperCase());
},
});
const out = [];
const sink = new Writable({
objectMode: true,
write(chunk, encoding, callback) {
out.push(chunk);
callback();
},
});
try {
await pipeline(Readable.from(["a", "b", "bad", "c"]), upper, sink);
} catch (error) {
console.log("failed:", error.message);
}
console.log(out);failed: bad chunk
[ 'A', 'B' ]c was never written, since the pipeline stopped at the bad chunk. The sink holds a partial result, and pipeline does not undo what was already written. If partial output is harmful, write to a temporary file and rename it only after the pipeline resolves.
Async generators as stages
Since Node.js 13.10, pipeline accepts async generator functions and async functions as stages. A generator in the middle transforms, and a function at the end acts as the sink. This removes most reasons to subclass Transform.
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
const lengths = [];
await pipeline(
Readable.from(["one", "three", "five"]),
async function* (source) {
for await (const word of source) {
yield word.length;
}
},
async function (source) {
for await (const length of source) lengths.push(length);
}
);
console.log(lengths);[ 3, 5, 4 ]An error thrown in either function rejects the pipeline and destroys the others, exactly as for class-based streams.
Cancellation with AbortSignal
Pass an options object with a signal as the last argument. Aborting destroys every stream and rejects with an AbortError.
import { Readable, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
const controller = new AbortController();
async function* forever() {
let n = 0;
while (true) yield String(n++);
}
const sink = new Writable({
write(chunk, encoding, callback) {
setImmediate(callback);
},
});
setTimeout(() => controller.abort(), 20);
try {
await pipeline(Readable.from(forever()), sink, { signal: controller.signal });
} catch (error) {
console.log(error.name, sink.destroyed);
}AbortError trueThis is the clean way to implement a timeout or a client disconnect: abort the signal, and the whole chain, including file handles and sockets, is released.
Early success is not an error
A stage can also stop on purpose. A generator that returns before its input ends finishes its own output normally, and the stages behind it are shut down without raising an error for the caller.
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
const taken = [];
await pipeline(
Readable.from([1, 2, 3, 4, 5]),
async function* (source) {
let count = 0;
for await (const n of source) {
yield n;
if (++count === 2) return;
}
},
async function (source) {
for await (const n of source) taken.push(n);
}
);
console.log(taken);[ 1, 2 ]The generator returned after two values, the final stage saw the end of its input, and the source was destroyed behind it.
Using pipeline with HTTP
The classic case is serving a file. If the client disconnects, the response is destroyed, and pipeline destroys the file stream, closing its descriptor.
import { createReadStream } from "node:fs";
import { createServer } from "node:http";
import { pipeline } from "node:stream/promises";
const server = createServer(async (request, response) => {
try {
await pipeline(createReadStream("./big-file.bin"), response);
} catch (error) {
console.log("download ended early:", error.code);
}
});
server.listen(3000);download ended early: ERR_STREAM_PREMATURE_CLOSEThe message appears when a client drops the connection mid-download, and the file descriptor is released. With pipe, the same disconnect leaves the file stream open and growing in memory.
Common mistakes
**Using pipe for anything that can fail.** Use pipeline.
**Forgetting await.** An un-awaited pipeline promise that rejects is an unhandled rejection.
Expecting a rollback. Written data stays written.
**Mixing pipe and pipeline in one chain.** Use one style.
Treating premature close as a bug. It is often just a client leaving.
Cleaning up partial output
Because pipeline does not undo writes, a chain that fails half way leaves partial data in its destination. For files, the standard approach is to write to a temporary path in the same directory and rename it to the final name only after the pipeline resolves, since a rename within one file system is atomic. For uploads to object storage, use the provider's multipart upload and abort it on failure. For database inserts, wrap the writes in a transaction and roll back on error. Whichever applies, put the cleanup in a catch or finally block around the await pipeline(...) call, where the error is visible.
Observing progress and errors
A stage can report progress without changing the data. A pass-through generator that counts bytes and logs every so often fits into any pipeline, and a Transform that emits an event is the class-based version of the same thing. For errors, remember that pipeline rejects with the first error and may produce others while it tears down the remaining streams. Those later errors are suppressed from the promise, so log them at the stream level if you need to see them all, using an error listener on each stream you create yourself.
Pipeline and the web streams API
Node.js also implements the web streams API, and stream.pipeline accepts web streams as well as classic ones, converting between them as needed. That makes it a good boundary tool when a library hands you a ReadableStream, such as the body of a fetch response, and you want to write it to a file with a classic Writable. Use Readable.fromWeb or pass the web stream straight to pipeline where the version supports it, and check the documentation for the exact conversions in your release.
Reading the error you get back
The error that pipeline rejects with is the original error from the failing stream, not a wrapper. That makes it easy to branch on its code or class, and it also means the stack points into the stream that failed, which is usually where you want to look first.


