The 'readable' Event and read() Method
You'll learn how to manually control data reading from a stream using the 'readable' event and read() method in paused mode.
When a Readable stream is in paused mode, data doesn't automatically flow to your code. Instead, you take control by listening for the 'readable' event, which signals that new data is available in the stream's internal buffer. You then explicitly call the read() method to pull out chunks of data.
Think of it like a buffet where food is ready (the 'readable' event fires), but you have to walk up and serve yourself (call read()) rather than having waiters bring food to your table automatically.
How It Works
When you attach a listener to the 'readable' event, the stream enters paused mode. The event fires whenever:
- New data has been pushed into the stream's buffer
- The stream has reached its end
Inside the event handler, you call stream.read() to retrieve data. This method returns a chunk of data (a Buffer by default) or null when there's nothing left to read at that moment.
The Pattern
const fs = require('fs');
const readable = fs.createReadStream('example.txt');
readable.on('readable', () => {
let chunk;
// Keep reading until read() returns null
while ((chunk = readable.read()) !== null) {
console.log(`Received ${chunk.length} bytes`);
}
});
readable.on('end', () => {
console.log('No more data');
});
You typically use a while loop to drain all available data because one 'readable' event might signal multiple chunks are ready.
Key Takeaway: The 'readable' event and read() method give you fine-grained control over when and how much data you pull from a stream in paused mode, useful when you need precise flow control or custom buffering logic.