node.js - 在客户端连接关闭时中止 ReadStream

标签 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 属性,我可以用它来停止进一步阅读的

我确实提供了属性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/

相关文章:

node.js - Azure 函数中的 Sharp 问题

javascript 重试异步等待

node.js - 在成功构建时增加 NPM/Grunt 版本 -- Bamboo

javascript - 安装node后在哪里可以找到node.js文件?

node.js - 如何正确地 unpipe nodejs 流

c++ - 从 std::cin 读取二进制数据

javascript - Node : Confusing behaviour related to saving a TypeORM model using await inside a callback/promises clearing

javascript - passportjs LocalStrategy 是否允许比默认用户名和密码更多的参数?

c++ - 多进程同步的输出流锁定?

php - 在 PHP 中解压缩 LZO 流