'readable' 事件何时实际发出? stream.Readable

When is 'readable' event actually emitted? stream.Readable

const stream = require('stream')
const readable = new stream.Readable({
    encoding: 'utf8',
    highWaterMark: 16000,
    objectMode: false
})

const news = [
    'News #1',
    'News #2',
    'News #3'
]

readable._read = () => {
    if(news.length) {
        return readable.push(news.shift() + '\n')
    }
    return readable.push(null)
}

readable.on('readable', () => {
    let data = readable.read()
    if(data) {
        process.stdout.write(data)
    }
})

readable.on('end', () => {
    console.log('No more feed')
})

为什么这段代码有效? 'readable' 当缓冲区中有一些数据时触发。如果我没有在流中推送任何数据,为什么这会起作用?我只在调用“_read”时阅读。我没有调用它,为什么它会触发可读事件?我是 node.js 的小白,刚开始学习。

如果您阅读文档,它会清楚地提到 readable._read(size) 此函数不得由应用程序代码直接调用。它应该由子 classes 实现,并且只能由内部可读 class 方法调用。

在您的代码中,您已经实现了 内部 _read,因此当您执行 readable.read() 代码时,您的实现被称为 internally 因此代码会执行。如果您在代码中注释掉 readable._read = ... 或重命名为其他内容,您将看到此错误:

Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented

同样来自文档:The 'readable' event is emitted when there is data available to be read from the stream. 因此,由于在您的代码中源 news 中有数据,事件将被触发。如果你不提供任何东西,比如 read() { },那么就没有地方可以读取,所以它不会被触发。

还有The 'readable' event will also be emitted once the end of the stream data has been reached but before the 'end' event is emitted.

假设您已经:

const news = null;

if(news) {
  return readable.push(news.shift() + '\n')
}
// this line is pushing 'null' which triggers end of stream
return readable.push(null)

然后触发 readable 事件,因为它已到达流的末尾,但 end 尚未触发。

您应该按照文档将 read 选项作为函数传递,read <Function> Implementation for the stream._read() method.

const stream = require('stream')
const readable = new stream.Readable({
    read() {
        if(news.length) {
            return readable.push(news.shift() + '\n')
        }
        return readable.push(null)
    },
    encoding: 'utf8',
    highWaterMark: 16000,
    objectMode: false
})