考虑以下相当简单的中间件:
(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()
}
有些问题我不确定如何处理:
close
或error
,源流是如何清理的? autoClose
只会在end
上运行,只有在读取了所有数据后才会运行destroy
。但是,如果目标失败,那么它是如何传播到源的?我应该始终在源流上调用var children = wrap.children().find( "div" );
吗?答案 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()
}