A push stream produces and enqueues data without waiting for the consumer to request it. In a JavaScript ReadableStream, a start method can enqueue values and close the stream when production is finished. If the consumer reads each value as soon as it arrives, the internal queue may stay small; that depends on the consumer’s pace. section 11.2.1
Listing 11.5 Creating a ReadableStream
import { setTimeout } from "node:timers/promises";
const ninjas = [
"Leonardo",
"Donatello",
"Raphael",
"Michelangelo",
];
const source = new ReadableStream<string>({
async start(controller) { #A
for (const ninja of ninjas) { #A
controller.enqueue(ninja); #A
await setTimeout(100); #A
} #A
controller.close(); #A
},
});
const received: string[] = []; #B
for await (const ninja of source) { #B
received.push(ninja); #B
} #B
console.assert(
received.length === 4,
"Four ninjas were received",
);
This ReadableStream enqueues four values from start, pauses between them, then closes; a for-await loop consumes them. section 11.2.1
A pull stream instead enqueues data when the consumer asks for it. The two approaches can look identical to consumers, but their production timing can affect performance. A stream can also combine start and pull, pushing initially and pulling later. section 11.2.1 section 11.3.1
Choose based on the work and resource tradeoffs:
- Push can suit parsing an entire XML file quickly; pull can suit extracting information from large files while minimizing memory use. section 11.3.1
- Do not assume a consumer’s high watermark controls a push source: for push streams it is only an optional hint and may have no effect. Check the stream’s documentation or implementation. section 11.3.2
