Intermediate Node.js Interview QuestionsIntermediatePractical
Node.js · Question 55
What is stream.pipeline in Node.js?
Direct answer
stream.pipeline (and stream/promises.pipeline) connects streams with proper error forwarding, cleanup, and backpressure — prefer it over manual .pipe() chains in production code.
pipeline() solves three pipe pitfalls — unhandled errors, missing destroy on failure, and broken backpressure across multiple transforms.
- Callback form — pipeline(a, b, c, (err) => { ... }) from node:stream.
- Promise form — await pipeline(a, b, c) from node:stream/promises.
- AbortSignal — optional signal destroys pipeline on timeout/cancel.
- Return value — promise resolves with { readable, writable } refs for last streams.
pipeline.mjs
import fs from "node:fs";
import { pipeline } from "node:stream/promises";
import { createGzip } from "node:zlib";
try {
await pipeline(
fs.createReadStream("export.ndjson"),
createGzip(),
fs.createWriteStream("export.ndjson.gz")
);
console.log("Pipeline finished");
} catch (err) {
console.error("Pipeline failed:", err.message);
}