Creating a Writable Stream
What you'll learn: How to build your own custom writable stream using Node.js's Writable constructor and implement the _write method.
The Core Idea
Just as you created a custom readable stream by extending Readable and implementing _read(), you create a custom writable stream by extending Writable and implementing _write(). The _write() method defines what happens with each chunk of data that gets written to your stream.
Think of it like designing a custom drain: you specify where the water (data) goes and what processing happens when it flows in.
Building Your Writable Stream
To create a writable stream, you:
- Import the
Writableclass from thestreammodule - Extend it with your custom class
- Implement the
_write(chunk, encoding, callback)method
The _write method receives three parameters:
- chunk: the data being written (Buffer or string)
- encoding: the character encoding (if chunk is a string)
- callback: a function you call when processing is complete (or with an error)
const { Writable } = require('stream');
class MyWritableStream extends Writable {
_write(chunk, encoding, callback) {
// Process the chunk
console.log('Writing:', chunk.toString());
// Signal completion (or pass an error if something went wrong)
callback();
}
}
const writable = new MyWritableStream();
writable.write('Hello ');
writable.write('World!');
writable.end();
You must call the callback() when you're done processing each chunk. This tells the stream it's safe to accept more data. If processing fails, pass an error: callback(error).
Key Takeaway: Custom writable streams extend the Writable class and implement _write(chunk, encoding, callback) to define how each piece of data is processed, always calling the callback to signal completion.