首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >何时实际发出“可读”事件?stream.Readable

何时实际发出“可读”事件?stream.Readable
EN

Stack Overflow用户
提问于 2019-03-30 15:36:29
回答 1查看 729关注 0票数 0
代码语言:javascript
复制
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')
})

为什么这段代码能工作?当缓冲区中有一些数据时,就会触发“可读”。如果我没有在流中推送任何数据,为什么要这样做呢?当“_read”被调用时,我才会阅读。我不叫它,它为什么要触发可读的事件?我是node.js的新手,刚刚开始学习。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-31 04:41:13

如果读取文档,它明确提到readable._read(size) --应用程序代码不能直接调用此函数。它应该由子类实现,并且仅由内部可读的类方法调用。

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

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

同样来自docs: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.

所以说你已经:

代码语言:javascript
复制
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选项作为函数传递给docs,read <Function> Implementation for the stream._read() method.

代码语言:javascript
复制
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
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55433016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档