首页 > 这是个什么问题?没毛病啊感觉

这是个什么问题?没毛病啊感觉


1.直接的bug就是1楼的同学说的
2.但是你在读文件的时候没用到流,所以我觉得你可以直接使用_this.res.end(data)可以避免你的问题
3.从你的代码中读出来几点意见给你

  const filePath=path.join(__dirname, 'xxxx.json')
  fs.lstat(filePath, (err, stats) => {
    if(err) return res.status(500).end('file is not founded')
    res.writeHead(200, {
      'Content-Type' : 'application/json',
    })
    const readStream = fs.createReadStream(filePath)
    readStream.on('end', () => {
      res.end()
    })
    readStream.on('error', (error) => {
      res.end(`read file stream error ${error.message}`)
    })
    readStream.pipe(res)
  })

随手写了一些, 你可以进行优化,打日志,或者用async解决callback hell问题等,还有头类型,返回的错误信息等,不过核心的流式吐出的代码应该没问题,仅供参考,希望对你有帮助


res.on('finish', res.end) 试一下


res.write()是异步的,所以上面代码执行书序是res.end()之后才真的是write。你可以在write的回调中调用end

【热门文章】
【热门文章】