我正在尝试发送一个(巨大)文件,每秒传递的数据量有限(使用 TooTallNate/node-throttle ):
var fs = require('fs');
var Throttle = require('throttle');
var throttle = new Throttle(64);
throttle.on('data', function(data){
console.log('send', data.length);
res.write(data);
});
throttle.on('end', function() {
console.log('error',arguments);
res.end();
});
var stream = fs.createReadStream(filePath).pipe(throttle);
如果我在客户端浏览器取消下载,流将继续,直到完全传输。
我还使用 npm node-throttled-stream 测试了上面的场景,相同的行为。
如果浏览器关闭了请求,如何取消流?
编辑:
我可以通过使用获取连接close
事件
req.connection.on('close',function(){});
但是 stream
既没有 destroy
也没有 end
或 stop
属性,我可以用它来停止进一步阅读的流
。
我确实提供了属性pause
Doc ,但我宁愿阻止 Node 读取整个文件,也不愿停止接收内容(如文档中所述)。
最佳答案
我最终使用了以下脏解决方法:
var aborted = false;
stream.on('data', function(chunk){
if(aborted) return res.end();
// stream contents
});
req.connection.on('close',function(){
aborted = true;
res.end();
});
如上所述,这并不是一个很好的解决方案,但它确实有效。
任何其他解决方案将不胜感激!
关于node.js - 在客户端连接关闭时中止 ReadStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17903393/