The _flush Method
You'll learn how to finalize processing in a Transform stream and handle any leftover data before the stream closes.
What Is _flush For?
When you create a Transform stream, the _transform method handles each chunk of data as it flows through. But what happens when the input ends and you still have some processing to do—maybe you've been accumulating data, or you need to emit one final chunk?
That's where _flush() comes in. It's an optional method that runs once, right after all input has been processed but before the stream officially ends. Think of it like closing out your work at the end of the day: you've handled all the tasks, but you need to file away notes or send one last email before leaving.
How It Works
The _flush method receives a callback parameter. You do your final work, optionally push any remaining data with this.push(), and then call callback() to signal you're done. If something goes wrong, call callback(error).
const { Transform } = require('stream');
const bufferTransform = new Transform({
_transform(chunk, encoding, callback) {
// Process chunks normally
this.push(chunk.toString().toUpperCase());
callback();
},
_flush(callback) {
// Emit final data before stream ends
this.push('\n--- END OF STREAM ---');
callback();
}
});
process.stdin.pipe(bufferTransform).pipe(process.stdout);
In this example, after all input finishes, _flush adds a footer message before the stream closes.
Key Takeaway:
The _flush method lets you handle cleanup and emit final data in a Transform stream after all input is consumed but before the stream ends—essential for stateful transformations or aggregations.