Paused vs Flowing Mode
You'll learn how readable streams operate in two distinct modes and how to control the flow of data between them.
The Two Modes
Readable streams in Node.js can operate in one of two modes that determine how data flows from the stream to your program:
Paused Mode (Pull): The stream waits passively. Data doesn't flow automatically—you must explicitly request it by calling read(). Think of this like a water faucet that's off: water is available, but you need to turn the handle each time you want some.
Flowing Mode (Push): The stream actively pushes data to your program as soon as it's available, triggering 'data' events automatically. This is like turning the faucet on full blast—water flows continuously until you stop it.
How Streams Switch Modes
A readable stream starts in paused mode by default. It switches to flowing mode when you:
- Attach a
'data'event listener - Call
.pipe()to connect it to a writable stream - Call
.resume()explicitly
You can return to paused mode by:
- Calling
.pause() - Removing all
'data'event listeners (if no pipe exists)
Why This Matters
The mode affects how you consume data. In paused mode, you control the pace—useful when processing needs to happen at a specific rate. In flowing mode, the stream controls the pace—efficient for scenarios where you want maximum throughput without manual intervention.
Understanding these modes helps prevent data loss and gives you fine-grained control over stream behavior.
Key Takeaway: Readable streams operate in paused mode (manual pull with read()) or flowing mode (automatic push via 'data' events), and you can switch between them using event listeners, pause(), and resume().