Streaming data conversion
Convert, filter, or enrich data while it flows through a pipeline.
Node.js · Class
The stream.Transform class is a Duplex stream whose readable output is computed from writable input. Custom transforms implement _transform() and may implement _flush() for final processing.
Transform is a Duplex stream that accepts writable input and produces readable output derived from that input. Subclasses or configured instances process each chunk through _transform, optionally perform final work in _flush, and signal completion through the callback.
new stream.Transform([options])| Name | Type | Description |
|---|---|---|
options | Object | Options passed to the Duplex constructor; the page documents Transform construction through the inherited stream options. |
A stream.Transform instance.
import { Transform } from 'node:stream';
const upper = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
}
});
upper.on('data', chunk => process.stdout.write(chunk));
upper.end('hello, transform!');Creates a transform stream that converts each input chunk to uppercase and emits the result.
Convert, filter, or enrich data while it flows through a pipeline.
Compress, encrypt, decrypt, or otherwise encode chunks incrementally.
Collect buffered state and emit a final result when input ends.
Transform extends Duplex, so it implements both writable and readable sides. Its output is computed from the input rather than merely forwarding it.
Follow-up: How would a transform emit several outputs for one input? Call the callback without output, then use push() for additional readable chunks before completing the operation.
Implement _transform(chunk, encoding, callback). Process the supplied chunk, then invoke callback with an optional error and optional output data.
Follow-up: What happens if processing is asynchronous? Delay the callback until the asynchronous work completes, and pass any failure as its error argument.
_flush() is optional and is used for work that must occur after all input has been processed. It can produce final output before the stream finishes.
Follow-up: When is _flush useful? Use it for buffered or aggregated state, such as emitting a final remainder after the last input chunk.
stream.Duplexstream.Readablestream.Writablestream.pipeline()stream.Transform._transform()stream.Transform._flush()