使用NodeJS正确发送文件

时间:2016-07-03 16:12:53

标签: javascript node.js express node-streams

考虑以下相当简单的中间件:

(req, res, next) => {
  const stream = fs.createReadStream(req.filePath)

  await new Promise((resolve, reject) => stream    
    .on('error', reject)
    .on('end', resolve)
    .pipe(res, { end: false })
    .on('error', reject)
    // 'close' is emitted if client prematurely disconnects.
    .on('close', resolve)
  res.end()
}

有些问题我不确定如何处理:

  • 如果res在此中间件运行之前已经发出'close',它将被卡住。
  • 如果重新发出closeerror,源流是如何清理的? autoClose只会在end上运行,只有在读取了所有数据后才会运行destroy。但是,如果目标失败,那么它是如何传播到源的?我应该始终在源流上调用var children = wrap.children().find( "div" ); 吗?

1 个答案:

答案 0 :(得分:0)

这似乎可以解决问题:

import onFinished from 'on-finished'

(req, res, next) => {
  const stream = fs.createReadStream(req.filePath)

  onFinished(res, () => stream.destroy && stream.destroy())

  if (onFinished.isFinished(res)) {
    return
  }

  await new Promise((resolve, reject) => stream    
    .on('error', reject)
    .on('end', resolve)
    .pipe(res, { end: false })
    .on('error', reject)
    // 'close' is emitted if client prematurely disconnects.
    .on('close', resolve)
  res.end()
}