2017-02-17 109 views
1

我管道到一个文件中的HTTPS请求,它的工作原理电话OK 99.9%,但偶尔(也许当服务器或网络不可用)无限期挂起......超时与node.js的处理流管道

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

我有其他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秒后超时,但它不会...

回答

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

```

也许你可以听那个事件?

+0

问题是,当'tansfer'结束时,'end'也被释放,不仅当它被中断或超时,我需要一种检测错误的方法。 – gabry