Connecting streams with pipeline
- Version
- 24
- Since
- 15.0.0
- Review
- Draft
Summary#
Use pipeline from node:stream/promises to move data from a readable source through zero or more transforms into a writable destination. The pipeline handles backpressure and gives you one promise for completion or failure.
Syntax#
import { pipeline } from "node:stream/promises";
await pipeline(source, transform, destination);
For a direct transfer, pass only the source and destination.
Example#
Save as tags.mjs and run node tags.mjs. Each chunk gets a tag= prefix before the destination collects it.
import { Readable, Transform, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
const colors = Readable.from(["amber", "indigo"]);
const tag = new Transform({
transform(chunk, _encoding, done) {
done(null, `tag=${chunk}\n`);
},
});
let output = "";
const collect = new Writable({
write(chunk, _encoding, done) {
output += chunk.toString();
done();
},
});
await pipeline(colors, tag, collect);
process.stdout.write(output);
Expected output#
tag=amber
tag=indigo
Common mistakes#
Wait for pipeline to fulfill before using the completed output. If a stage fails, the promise rejects and the pipeline destroys streams that are still active. Use fresh streams for a retry.
Version applicability#
Node.js 15.0.0 introduced the promise form used here and is the minimum for the example. The older callback form of pipeline was introduced in 10.0.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0