node.js - 使用 Node.js 流管道进行超时处理

标签 node.js error-handling stream timeout pipe

我正在向文件传输 HTTPS 请求,99.9% 的调用都可以正常工作,但偶尔(也许当服务器或网络不可用时)会无限期挂起...

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

我有其他 https 连接,以前偶尔会挂起,但现在总是在请求对象上使用以下错误代码完成,如 Node 文档中所建议的:

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

```

也许你可以听一下那个事件?

关于node.js - 使用 Node.js 流管道进行超时处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42301512/

相关文章:

php - PHP foreach循环,带有循环错误消息

c# - 使用 Stream.Read() 与 BinaryReader.Read() 处理二进制流

java - java中的流关闭异常

stream - 在 kurento 媒体服务器中混合流概念

indexing - 有没有快速的解决方案来从 Node.js 查询 Lucene 索引?

node.js - Sequelize : how to get datetime column value as string

Node.js/Redis - 等待连接?

node.js - Swisscom应用云 Node 版本

actionscript-3 - 如何使Flashdevelop错误出现在结果面板中?

php - 在MySQLi中使用if/else的回显错误