2

我正在尝试发送一个(巨大的)文件,每秒通过的数据量有限(使用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(){});

但是 thestream既没有 adestroy也没有endorstop属性,我可以用它来阻止stream进一步阅读。

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

4

1 回答 1

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();
});

如上所述,这并不是一个很好的解决方案,但它确实有效。
任何其他解决方案将不胜感激!

于 2013-11-19T20:12:29.993 回答