当 readStream 结束或出现错误时,写入流也会结束。您可以通过传递来防止这种默认行为end:false
在管道期间并手动结束写入流。
因此,即使发生错误,您的写入流仍然打开,您可以使用 writestream 中的 writestream 执行其他操作(例如发送 404 状态)error
打回来。
var readStream = fs.createReadStream('/saved-files/' + request.params.id);
readStream.on('error', function () {
res.status(404).end();
});
readStream.on('end', function(){
res.end(); //end write stream manually when readstream ends
})
readStream.pipe(res,{end:false}); // prevent default behaviour
Update 1:对于文件流,可以监听open
检查文件是否准备好读取的事件:
readStream.on('open', function () {
// set response headers and status
});
Update 2:正如OP提到的,可能没有open
对于其他流的事件,如果流是从节点的流模块继承的,我们可以使用以下内容。诀窍是我们手动写入数据而不是pipe()
方法。这样我们就可以在开始写入第一个字节之前对可写进行一些“初始化”。
所以我们绑定once('data')
先绑定再绑定on('data')
。第一个将在实际写入之前被调用。
readStream
.on('error',function(err) {
res.status(404).end();
})
.once('data',function(){
//will be called once and before the on('data') callback
//so it's safe to set headers here
res.set('Content-Type', 'text/html');
})
.on('data', function(chunk){
//now start writing data
res.write(chunk);
})
.on('end',res.end.bind(res)); //ending writable when readable ends