What is the node:stream module's Transform stream, and how does it differ from a Readable or Writable stream?
Short answer
A Transform stream is both readable and writable, taking input, transforming it (via a required _transform() method), and making the result readable out the other side -- unlike a plain Readable or Writable, it sits naturally in the middle of a pipeline, standard for…
Advertisement
AModel answer
A Transform stream is both readable and writable, taking input, transforming it (via a required _transform() method), and making the result readable out the other side -- unlike a plain Readable or Writable, it sits naturally in the middle of a pipeline, standard for compression, encryption, or format conversion as streaming steps.
const uppercaseTransform = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk.toString().toUpperCase());
callback();
},
});
readableStream.pipe(uppercaseTransform).pipe(writableStream);Real-world example
A log-processing pipeline pipes raw log lines through a custom Transform that redacts sensitive fields, processed incrementally without loading the entire file into memory.
Likely follow-ups
- What is the difference between a Transform stream's 'transform' mode and its 'flush' behavior?
- How would you implement a Transform that buffers multiple chunks before producing output, like a line-splitter?
Related topics