两种读取模式
【Two reading modes】
Readable 流实际上有两种工作模式:流动模式和暂停模式。这些模式与 对象模式 无关。Readable 流可以处于对象模式,也可以不处于对象模式,无论它是处于流动模式还是暂停模式。
- 在流模式下,数据会自动从底层系统读取,并通过
EventEmitter接口使用事件尽可能快速地提供给应用。 - 在暂停模式下,必须显式调用
stream.read()方法从流中读取数据块。
所有 Readable 流都是以暂停模式开始的,但可以通过以下方式之一切换到流动模式:
【All Readable streams begin in paused mode but can be switched to flowing
mode in one of the following ways:】
- 添加一个
'data'事件处理程序。 - 调用
stream.resume()方法。 - 调用
stream.pipe()方法将数据发送到Writable。
Readable 可以使用以下方法之一切换回暂停模式:
【The Readable can switch back to paused mode using one of the following:】
- 如果没有管道目标,可以调用
stream.pause()方法。 - 如果有管道目标,可以通过删除所有管道目标来实现。可以通过调用
stream.unpipe()方法来删除多个管道目标。
需要记住的重要概念是,Readable 不会生成数据,除非提供了用于消费或忽略该数据的机制。如果消费机制被禁用或移除,Readable 将尝试停止生成数据。
【The important concept to remember is that a Readable will not generate data
until a mechanism for either consuming or ignoring that data is provided. If
the consuming mechanism is disabled or taken away, the Readable will attempt
to stop generating the data.】
出于向后兼容的原因,移除 'data' 事件处理程序不会自动暂停流。此外,如果存在管道目标,那么调用 stream.pause() 并不能保证在这些目标消耗完数据并请求更多数据后,流会_保持_暂停状态。
【For backward compatibility reasons, removing 'data' event handlers will
not automatically pause the stream. Also, if there are piped destinations,
then calling stream.pause() will not guarantee that the
stream will remain paused once those destinations drain and ask for more data.】
如果将 Readable 切换到流动模式,而没有可用的消费者来处理数据,那么这些数据将会丢失。例如,当调用 readable.resume() 方法而没有为 'data' 事件附加监听器,或者从流中移除了 'data' 事件处理程序时,就可能发生这种情况。
【If a Readable is switched into flowing mode and there are no consumers
available to handle the data, that data will be lost. This can occur, for
instance, when the readable.resume() method is called without a listener
attached to the 'data' event, or when a 'data' event handler is removed
from the stream.】
添加 'readable' 事件处理程序会自动使流停止流动,数据必须通过 readable.read() 消耗。如果移除 'readable' 事件处理程序,那么如果存在 'data' 事件处理程序,流将会再次开始流动。
【Adding a 'readable' event handler automatically makes the stream
stop flowing, and the data has to be consumed via
readable.read(). If the 'readable' event handler is
removed, then the stream will start flowing again if there is a
'data' event handler.】