Course contentsShow
← JavaScript
Lesson 1565 of 2,72334. Streams and BuffersFree lesson

Implementing the _transform Method

Writing the core transformation logic that processes chunks and pushes output.

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:

  1. Process that chunk (modify, filter, parse, etc.)
  2. Push zero or more transformed chunks to the output
  3. 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, or callback(error) if something fails
  • You can push null to signal the end of the stream
  • The encoding parameter is typically 'buffer' unless you set decodeStrings: 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.