import { Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import fs from "node:fs";
const upper = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
},
});
await pipeline(
fs.createReadStream("in.txt"), upper, fs.createWriteStream("out.txt")
);
A Transform stream implements transform(chunk, encoding, callback). Follow these rules:
- Push output with
this.push(), or pass it as the second argument tocallback. - Call
callbackexactly once for each chunk. - To fail the stream, pass an error as the first argument to
callback. - An optional
flush(callback)runs at the end. Use it to emit any leftover buffered data.
pipeline connects the read stream, the transform and the write stream. It handles backpressure (a fast source waiting for a slow destination). It rejects if any of the streams fails.
Note: converting each chunk on its own is only safe here because ASCII case mapping never splits across chunks. For multi-byte text, set an encoding on the source or use a StringDecoder. This stops characters from being cut in half at a chunk boundary.
- Implement
transform(chunk, encoding, callback). - Call
callbackonce per chunk, and pass an error to fail the stream. - Use the optional
flushmethod to emit leftover data. - Connect the streams with
pipelineto handle backpressure and errors.
Read more