【问题标题】:Timeout handling with node.js stream piping使用 node.js 流管道处理超时
【发布时间】:2017-07-07 04:35:19
【问题描述】:

我正在向一个文件发送 HTTPS 请求,它在 99.9% 的调用中都可以正常工作,但偶尔(可能在服务器或网络不可用时)会无限期挂起......

这显然会导致我的应用程序停止工作并需要手动重启...

我有其他 https 连接,这些连接过去偶尔会挂起,现在总是使用请求对象上的以下错误代码完成,正如节点文档中所建议的那样:

request.on('socket', function(socket) {
    socket.setTimeout(10000);
    socket.on('timeout', function() { request.abort(); });
});

request.on('error', function(e) {
   // Handle the error...
   console.error("FAILED!");
});

...但是如果将目标通过管道传输到文件流,请求的超时似乎会被忽略,也许我应该处理文件系统对象超时的错误,但文档不清楚是否存在除了“完成”之外,我必须等待的事件......

这是示例代码,希望有人能帮助我:

var https = require('https'),
    fs = require('fs');

var opts = {
        host: 'www.google.com',
        path: '/',
        method: 'GET',
        port: 443
};

var file = fs.createWriteStream('test.html');

var request = https.request(opts, function(response) {
    response.pipe(file);
    file.on('finish', function() {
        file.close(function(){
            console.log("OK!");
        });
    });
 });

request.on('socket', function(socket) {
    socket.setTimeout(10000);
    socket.on('timeout', function() { request.abort(); });
});

request.on('error', function(e) {
  console.error("FAILED!");
});

request.end();

如果你想尝试挂起,用一个大文件更改主机路径并在传输过程中断开网线,它应该在10秒后超时,但是它没有……

【问题讨论】:

    标签: node.js error-handling stream timeout pipe


    【解决方案1】:

    我设置了一个演示 node.js http 服务器,它发送一个非常慢的答案和一个类似于您的示例代码的客户端。

    当我启动客户端然后在发送响应时停止服务器时,我也没有在套接字上收到 timeout 事件,但我在客户端的响应中收到 end 事件:

    var request = https.request(opts, function(response) {
        response.pipe(file);
        file.on('finish', function() {
            file.close(function(){
               console.log("OK!");
            });
        });
        response.on('end', function() {
           // this is printed when I stop the server
           console.log("response ended");
        });
     });
    

    ```

    也许你可以听听那个活动?

    【讨论】:

    • 问题是在传输结束时也会发出“end”,不仅是在中断或超时时,我需要一种检测错误的方法。
    猜你喜欢
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    相关资源
    最近更新 更多