Stream in Nodejs

reference: https://nodesource.com/blog/understanding-streams-in-nodejs/

Advantage:

  • In a http example, do not need to put all file size into memories anymore
  • prevent the low response speed or even crash caused by memory's over-limited
  • process one chunk data each time

Principle:

Event Emitter of Node.js

Category:

  • readable:可读
  • writable:可写
  • duplex:双工。可读也可写,互不干扰。
  • transform:转换。从可写转成可读,链式调用,做数据处理

Implement:

  1. native api:
  • stream
  • fs.createReadStream
  • http
  • socket
  • process.stdin(out)
  • zlib.createGzip: one of the most common transform stream
  1. inherit
    to diy your own specific stream:
  • inherit class (like Readable)
  • redefine _read function

API:

  • pipe/unpipe
  • pipeline: multiple process in one line
  • resume/pause
  • push
  • event:
    readable, data,
    error, finish, close, drain

Concept :

  • mode: flowing & pause and several related events
  • back pressure:背压,eg: 写不进去,wait the drain(下水道) event to continue

Streams Cheat Sheet:

fundamental

practice

flowing

readable & transform

writable & compound
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...
    KeKeMars阅读 6,366评论 0 6
  • 什么是流? 流是一种用来处理文件的字节传输手段 它不关心文件的整体内容,只关注是否从文件中读取到了数据,以及读到数...
    seventhMa阅读 997评论 0 0
  • 简单介绍流 一般处理数据有两种模式, buffer模式和stream模式, buffer模式就是取完数据一次性操作...
    裤裤他爸阅读 409评论 0 0
  • 姓名:刘强 公司:宁波大发化纤有限公司 六项精进第277期利他四组学员 【日精进打卡第81天】,共计81天。 【知...
    三分厂刘强阅读 107评论 0 0
  • 稚嫩和沧桑用我不理解的方式集中在他的面孔,不愿去猜测他的年龄,或者说不敢,这位目不转睛盯着小孩子手中即将喝空饮料瓶...
    贪杯的灵魂阅读 510评论 0 0