在客户端连接关闭中止ReadStream

时间:2013-07-27 23:13:27

标签: node.js stream

我正在尝试发送一个(巨大的)文件,每秒传递一定数量的数据(使用 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也没有endstop属性,我可以使用它来阻止stream进一步阅读。

我确实提供了属性pause Doc ,但我宁愿停止节点阅读整个文件而不是停止接收内容(如文档中所述)。

1 个答案:

答案 0 :(得分:1)

我最终使用了以下解决方法:

var aborted = false;

stream.on('data', function(chunk){
    if(aborted) return res.end();

    // stream contents
});

req.connection.on('close',function(){
    aborted = true;
    res.end();
});

如上所述,这不是一个很好的解决方案,但它有效 任何其他解决方案将受到高度赞赏!

相关问题