美文网首页
nodejs stream

nodejs stream

作者: RickyWu585 | 来源:发表于2022-02-22 09:30 被阅读0次

    为什么需要stream

    • 不用stream的情况:太耗内存
    const fs = require('fs')
    const http = require('http')
    
    const server = http.createServer()
    server.on('request',(request,response)=>{
      fs.readFile('./big_file.txt',(error,data)=>{
        if(error)throw error
        response.end(data)
        console.log('done')
      })
    })
    server.listen(8888)
    
    • 优化:用pipe连接读文件流http可写流
      image.png
    const fs = require('fs')
    const http = require('http')
    
    const server = http.createServer()
    server.on('request',(request,response)=>{
      const stream = fs.createReadStream('./big_file.txt')
      stream.pipe(response)
      stream.on('end',()=>console.log('done'))
    })
    server.listen(8888)
    
    • 管道等同于以下事件:


      image.png
    • stream其实是个事件,可读流有data,end等事件,data事件回调参数chunk二进制buffer,如果想要转译的话,用toString()

    const fs = require('fs')
    const http = require('http')
    
    const server = http.createServer()
    server.on('request',(request,response)=>{
      const stream = fs.createReadStream('./big_file.txt')
      stream.on('data',(chunk)=>{
        console.log('读取了一次数据')
        console.log(chunk.toString())
      })
      stream.on('end',()=>{
        console.log('全部读取完了')
      })
    })
    server.listen(8888)
    

    stream分类:

    • Readable:可读
    • Writable:可写
    • Duplex:可读可写(双向)
    • Transform:可读可写(变化),例如babel,scss转译等

    Readable Stream:

    • 静止态paused和流动态flowing
    • 默认处于paused
    • 添加data事件监听,就变成flowing
    • 删掉data事件监听,就变成paused
    • pause()可以将它变为paused
    • resume()可以将它变为flowing

    Writable Stream:

    • drain事件:
      调用stream.write(chunk)可能会得到false,表示数据积压了,这时就不能再write了,要监听drain事件,等drain事件触发了即数据不积压了,才能继续write

    相关文章

      网友评论

          本文标题:nodejs stream

          本文链接:https://www.haomeiwen.com/subject/gjgvkrtx.html