Implementing the _transform Method
You'll learn how to write the core logic that processes data chunks flowing through a Transform stream.
What It Does
The _transform method is the heart of any custom Transform stream. It's called automatically for each chunk of data that enters the stream, and your job is to:
- Process that chunk (modify, filter, parse, etc.)
- Push zero or more transformed chunks to the output
- Signal when you're done processing that chunk
Think of it like a factory worker on an assembly line: you receive a raw part, modify it, and pass it along to the next station.
The Method Signature
When you extend the Transform class, you implement _transform with this signature:
_transform(chunk, encoding, callback) {
// chunk: the data to process (Buffer or string)
// encoding: if chunk is string, this tells you which encoding
// callback: call this when done processing
// Transform the chunk
const transformed = chunk.toString().toUpperCase();
// Push it to the output
this.push(transformed);
// Signal completion
callback();
}
Key Points
- Push output using
this.push(data)— you can call it multiple times, or not at all if you're filtering - Always call
callback()when done, orcallback(error)if something fails - You can push
nullto signal the end of the stream - The
encodingparameter is typically'buffer'unless you setdecodeStrings: false
Key Takeaway: The _transform method receives chunks, processes them with your custom logic, pushes transformed output using this.push(), and must always invoke the callback() to signal completion or errors.