事件:'data'
【Event: 'data'】
chunk<Buffer> | <string> | <any> 数据块。对于不以对象模式运行的流,数据块将是字符串或Buffer。对于以对象模式运行的流,数据块可以是任意 JavaScript 值,但不能是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.`);
});