Write a Transform stream that converts incoming text to uppercase.
Extend stream.Transform (or pass a transform function), call this.push with the changed chunk, and call the callback when done. Then pipe a readable into it and into a writable.
Explain it simply
A Transform stream is a small machine on an assembly line. Raw material arrives as chunks, the machine changes each chunk, and the result flows to the next step. You only describe what happens to one chunk; Node handles the buffering and flow control.
Example
const { Transform, pipeline } = require("stream");
const upper = new Transform({
transform(chunk, encoding, callback) {
// chunk is a Buffer by default
callback(null, chunk.toString().toUpperCase());
},
});
pipeline(process.stdin, upper, process.stdout, (err) => {
if (err) console.error("pipeline failed", err);
});
// echo "jai hind" | node upper.js
// prints: JAI HINDcallback(null, data) is shorthand for this.push(data) followed by callback(). To drop a chunk, call callback() with no data. To fail, call callback(error).
If a transform must emit something at the very end, such as a summary line, add a flush(callback) method, which runs after the last chunk.
Line by line
new Transform({ transform })creates the stream with our logic.chunk.toString().toUpperCase()converts the bytes to text and changes it.callback(null, ...)passes the result downstream and asks for the next chunk.pipelinejoins stdin, our stream and stdout, and reports errors.
A chunk boundary may split a multi-byte character such as a Hindi letter. For text, use StringDecoder or set decodeStrings carefully.
Complexity
Time O(n) in the input size; memory O(chunk size), because only one chunk is held at a time.
What to say in the interview
"I create a Transform with a transform(chunk, enc, cb) function that calls cb with the converted data, then use pipeline to connect source and destination. flush handles end-of-stream work."
Common mistakes
- Forgetting to call the callback, which stalls the stream.
- Assuming a chunk always holds complete lines or characters.