在Node.js官网API中,关于readable._read(size)的疑问?

在学习Node.js的时候,查看官网文档,关于readable._read(size)这个API,官网中有如下的这段话:
When _read is called, if data is available from the resource, _read should start pushing that data into the read queue by calling this.push(dataChunk). _read should continue reading from the resource and pushing data until push returns false, at which point it should stop reading from the resource. Only when _read is called again after it has stopped should it start reading more data from the resource and pushing that data onto the queue.

Note: once the _read() method is called, it will not be called again until the push method is called.

问题如下:

  1. 为什么_read会触发push操作?

  2. _read为什么会设计成关联push的操作?

阅读 3k
1 个回答

1)_read方法作为底层借口由你自己实现readable接口的时候实现,不能直接调用
2)_read方法从底层数据流中读取数据内容,然后通过push方法放入用户的数据消费队列中,直到用户数据消费队列满。此时数据的读取动作就为停止。
3)当用户消费队列中的数据在用户通过监听data事件获取到后,_read方法会被再次调用,填充用户数据消费队列
4)这个过程一直持续到读到数据末尾位置

_read方法是需要在实现自己的readable流对象的时候实现的,是底层系统调用触发的。你不好直接调用~~~

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题