【问题标题】:Nodejs Readable stream, Not working response using pipe in expressjsNodejs可读流,在expressjs中使用管道无法响应
【发布时间】:2021-11-06 22:17:01
【问题描述】:

我想使用 nodejs 中的流发送数据。我尝试使用管道发送数据,但没有成功,请帮助我。

const { Readable } = require("stream")

app.get('/test',async (req,res)=>{

  let month = ['jan','feb','mar','apr','may','jun','jul'];
  let stream = new Readable({read(size){}});
  stream.setEncoding('utf8')
  
  for(let m of month) {
    stream.push(m)
  }
   
  stream.on('data',(data) => {
    console.log(data)
    res.write(data,'utf8')
  })

  stream.on('end',() => {
    res.end();
  })
  
})

我也试过了,但是没用……

const { 可读 } = require("stream")

app.get('/test',async (req,res)=>{

  let month = ['jan','feb','mar','apr','may','jun','jul'];
  let stream = new Readable({read(size){}});
  stream.setEncoding('utf8')
  
  for(let m of month) {
    stream.push(m)
  }
  
  stream.pipe(res)
  
})

【问题讨论】:

标签: node.js express


【解决方案1】:

您还必须在for 循环之后以stream.push(null) 结束流。见https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_readable_push_chunk_encoding

将块作为 null 传递表示流结束 (EOF),在此之后无法写入更多数据。

【讨论】:

    猜你喜欢
    • 2019-07-12
    • 2015-05-03
    • 2022-01-03
    • 2023-03-21
    • 1970-01-01
    • 2019-10-10
    • 2021-09-15
    • 2017-08-25
    • 2013-07-11
    相关资源
    最近更新 更多