Writable Streams
⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 3 min
TL;DR
A Writable stream is a destination where data can be written. You write data in chunks, and if the destination is slower than the incoming data, you must handle backpressure.
Mental Model
How It Works
You write data using the write() method.
If write() returns true, the data was processed or safely buffered, and you can keep writing.
If write() returns false, it means the internal buffer is full (it has reached the highWaterMark). You should stop writing and wait for the 'drain' event to be emitted before continuing.
Example
const fs = require('fs');
const writable = fs.createWriteStream('output.txt');
// Simple usage
writable.write('Hello, ');
writable.write('World!');
writable.end(); // Signals no more data will be written
writable.on('finish', () => {
console.log('All data has been flushed to the file.');
});
Common Interview Questions
What is the difference between 'finish' and 'drain' events?
'drain'is emitted when the stream’s internal buffer has emptied, signaling it’s safe to resume writing (used for managing backpressure).'finish'is emitted afterstream.end()has been called and all buffered data has successfully been flushed to the underlying system.
How do you implement a custom Writable stream?
By extending the Writable class from node:stream and implementing the _write(chunk, encoding, callback) method. You must call callback() when you are done processing the chunk to signal success, or callback(err) if an error occurred.