事件:'readable'
【Event: 'readable'】
'readable' 事件在流中有可读取的数据时触发,直到达到配置的高水位标记(state.highWaterMark)。实际上,它表示流的缓冲区中有新的信息。如果缓冲区中有数据,可以调用 stream.read() 来获取这些数据。此外,当流的末端已经到达时,也可能会触发 'readable' 事件。
【The 'readable' event is emitted when there is data available to be read from
the stream, up to the configured high water mark (state.highWaterMark). Effectively,
it indicates that the stream has new information within the buffer. If data is available
within this buffer, stream.read() can be called to retrieve that data.
Additionally, the 'readable' event may also be emitted when the end of the stream has been
reached.】
const readable = getReadableStreamSomehow();
readable.on('readable', function() {
// There is some data to read now.
let data;
while ((data = this.read()) !== null) {
console.log(data);
}
}); 如果已经到达流的末端,调用 stream.read() 将返回 null 并触发 'end' 事件。如果根本没有任何数据可供读取,这同样适用。例如,在下面的例子中,foo.txt 是一个空文件:
【If the end of the stream has been reached, calling
stream.read() will return null and trigger the 'end'
event. This is also true if there never was any data to be read. For instance,
in the following example, foo.txt is an empty file:】
const fs = require('node:fs');
const rr = fs.createReadStream('foo.txt');
rr.on('readable', () => {
console.log(`readable: ${rr.read()}`);
});
rr.on('end', () => {
console.log('end');
}); 运行此脚本的输出是:
【The output of running this script is:】
$ node test.js
readable: null
end 在某些情况下,为 'readable' 事件附加监听器会导致一定量的数据被读取到内部缓冲区中。
【In some cases, attaching a listener for the 'readable' event will cause some
amount of data to be read into an internal buffer.】
总体而言,readable.pipe() 和 'data' 事件机制比 'readable' 事件更容易理解。然而,处理 'readable' 可能会提高吞吐量。
【In general, the readable.pipe() and 'data' event mechanisms are easier to
understand than the 'readable' event. However, handling 'readable' might
result in increased throughput.】
如果同时使用 'readable' 和 'data','readable' 在控制流程时具有优先权,即只有在调用 stream.read() 时才会触发 'data'。readableFlowing 属性将变为 false。如果在移除 'readable' 时存在 'data' 监听器,流将开始流动,即无需调用 .resume() 就会触发 'data' 事件。
【If both 'readable' and 'data' are used at the same time, 'readable'
takes precedence in controlling the flow, i.e. 'data' will be emitted
only when stream.read() is called. The
readableFlowing property would become false.
If there are 'data' listeners when 'readable' is removed, the stream
will start flowing, i.e. 'data' events will be emitted without calling
.resume().】