【问题标题】:How to detect client closing connection during piping stream over http in node?如何在节点中通过http的管道流期间检测客户端关闭连接?
【发布时间】:2015-10-13 17:21:39
【问题描述】:

我在 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);
}

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

【问题讨论】:

    标签: javascript node.js http express stream


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我会在接受之前尝试一下,但是您的回复很有用!
    猜你喜欢
    • 2020-05-30
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多