三种状态


【Three states】

Readable 流的“两种模式”操作是对 Readable 流实现中更复杂的内部状态管理的一种简化抽象。

【The "two modes" of operation for a Readable stream are a simplified abstraction for the more complicated internal state management that is happening within the Readable stream implementation.】

具体来说,在任意时刻,每个 Readable 都处于三种可能状态之一:

【Specifically, at any given point in time, every Readable is in one of three possible states:】

  • readable.readableFlowing === null
  • readable.readableFlowing === false
  • readable.readableFlowing === true

readable.readableFlowingnull 时,不会提供用于消费流数据的机制。因此,流将不会生成数据。在这种状态下,附加 'data' 事件的监听器、调用 readable.pipe() 方法或调用 readable.resume() 方法将会把 readable.readableFlowing 改为 true,使 Readable 开始在生成数据时主动触发事件。

【When readable.readableFlowing is null, no mechanism for consuming the stream's data is provided. Therefore, the stream will not generate data. While in this state, attaching a listener for the 'data' event, calling the readable.pipe() method, or calling the readable.resume() method will switch readable.readableFlowing to true, causing the Readable to begin actively emitting events as data is generated.】

调用 readable.pause()readable.unpipe() 或遇到背压(backpressure)会导致 readable.readableFlowing 被设置为 false,暂时停止事件的流动,但不会停止数据的生成。在这种状态下,附加 'data' 事件的监听器不会将 readable.readableFlowing 切换为 true

【Calling readable.pause(), readable.unpipe(), or receiving backpressure will cause the readable.readableFlowing to be set as false, temporarily halting the flowing of events but not halting the generation of data. While in this state, attaching a listener for the 'data' event will not switch readable.readableFlowing to true.】

const { PassThrough, Writable } = require('node:stream');
const pass = new PassThrough();
const writable = new Writable();

pass.pipe(writable);
pass.unpipe(writable);
// readableFlowing is now false.

pass.on('data', (chunk) => { console.log(chunk.toString()); });
// readableFlowing is still false.
pass.write('ok');  // Will not emit 'data'.
pass.resume();     // Must be called to make stream emit 'data'.
// readableFlowing is now true. 

readable.readableFlowingfalse 时,数据可能会在流的内部缓冲区中积累。

【While readable.readableFlowing is false, data may be accumulating within the stream's internal buffer.】