A Readable is a Node.js stream producer: it wraps a data source and exposes chunks incrementally. The surprising part is that it does not start producing immediately. It begins in a null state, then becomes flowing or paused according to how the consumer attaches. section 10.3.1
Track the stream through three states:
- Null: no data has begun flowing because the consumer's preferred consumption mode is unknown. section 10.3.1
- Flowing: attaching a data handler or calling resume() causes repeated reads and emits a data event for each pushed chunk. section 10.3.1
- Paused: pause() stops data events while chunks accumulate in the internal buffer; resume() restores flowing mode. section 10.3.1
- End production by passing null to push(). section 10.3.1
const stream = require('node:stream');
let count = 0;
const r = new stream.Readable({
read() {
this.push('hello'); #A
if (++count === 5) {
this.push(null); #B
}
}
});
r.on('data', console.log); #CThe runnable pattern defines read() as the producer, pushes five chunks, ends with null, and starts consumption by attaching a data listener. section 10.3.1
Readable streams remain push-driven internally even when consumed with for-await-of. Symbol.asyncIterator lets the loop pull one chunk at a time from the internal buffer, while buffering and backpressure coordinate the source. The syntax resembles pure pull reading, but the underlying hose still fills the buffer. section 10.5.3
const readable = fs.createReadStream('large-file.txt');
for await (const chunk of readable) {
await processChunk(chunk);
}This pattern consumes a file Readable incrementally and awaits processing for each chunk, exposing the async-iteration bridge directly. section 10.5.3
