事件:'data'


¥Event: 'data'

  • chunk <Buffer> | <string> | <any> 数据块。对于不在对象模式下操作的流,块将是字符串或 Buffer。对于处于对象模式的流,块可以是除 null 之外的任何 JavaScript 值。

    ¥chunk <Buffer> | <string> | <any> The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or Buffer. For streams that are in object mode, the chunk can be any JavaScript value other than null.

每当流将数据块的所有权移交给消费者时,则会触发 'data' 事件。每当通过调用 readable.pipe()readable.resume()、或通过将监听器回调绑定到 'data' 事件而将流切换到流动模式时,就会发生这种情况。每当调用 readable.read() 方法并且可以返回数据块时,也会触发 'data' 事件。

¥The 'data' event is emitted whenever the stream is relinquishing ownership of a chunk of data to a consumer. This may occur whenever the stream is switched in flowing mode by calling readable.pipe(), readable.resume(), or by attaching a listener callback to the 'data' event. The 'data' event will also be emitted whenever the readable.read() method is called and a chunk of data is available to be returned.

'data' 事件监听器绑定到尚未显式暂停的流,则会将流切换到流动模式。数据将在可用时立即传入。

¥Attaching a 'data' event listener to a stream that has not been explicitly paused will switch the stream into flowing mode. Data will then be passed as soon as it is available.

如果使用 readable.setEncoding() 方法为流指定了默认编码,则监听器回调将把数据块作为字符串传递;否则数据将作为 Buffer 传递。

¥The listener callback will be passed the chunk of data as a string if a default encoding has been specified for the stream using the readable.setEncoding() method; otherwise the data will be passed as a Buffer.

const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
});