liveBook · Manning

Readable API

As explained in JavaScript in Depth

A Node.js stream object that exposes incrementally produced data for consumption.

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);  #C

The 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

How JavaScript in Depth covers it

How deep it goes
Traces null, flowing, and paused states, buffering, termination, and the push-to-pull bridge, but not source implementation details.
Examples
Uses a custom Readable that pushes hello five times and a file stream consumed with for-await-of.
What it assumes
Assumes JavaScript event handling and async iteration, while teaching stream states and their buffering behavior.
What you can do after
Operate/configure Readable streams with push(), data handlers, pause(), resume(), and for-await-of.
How it connects
Connects Readable streams with Writable streams, Transform streams, backpressure, async iteration, and Web Streams.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.