javascript - 如何在 Node 中通过 http 管道流检测客户端关闭连接?

标签 javascript node.js http express stream

我在 expressjs (nodejs) 应用程序中将数据从服务器流式传输到客户端。

我做了这样的事情;

// let contentType and filename be correctly defined in context

function(req,res){
    res.setHeader('Content-Type',contentType);
    res.setHeader('Content-Disposition','attachment; filename='+filename);
    require('fs').createReadStream('/path/file').pipe(res);
}

我想知道客户端何时无法下载文件,但我不知道如何继续。

最佳答案

监听响应对象上的 close 事件。当与客户端的连接过早关闭(如刷新页面或关闭选项卡)时会发出此消息。

require('fs').createReadStream('/path/file').pipe(res).on('close',function(){
   //do stuff for closed connection
})

关于javascript - 如何在 Node 中通过 http 管道流检测客户端关闭连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586763/

相关文章:

api - 使用 http api 发布到默认的 rabbitmq exchange

javascript - 无法在 shopify 库中获得可拖放的工作

node.js - 在 mongodb 中保存或更新文档时如何防止更新 "updatedAt"字段?

node.js - MongoJS 增加池大小

node.js - Express/Socket.io : The right way for one socket per request

node.js - HTTP POST Google Cloud Functions NodeJS

javascript - 为什么我的代码不使用 jquery 更改光标?

javascript - D3 JS 工具提示触发鼠标悬停事件

javascript - 使用 child_process exec 时断言在 mocha 中不起作用

java - 为什么 TestRestTemplate 会忽略 404 客户端错误?