nodejs, http.request超时控制

场景: 使用nodejs请求外部网页,要求规定时间内返回
依赖库: http/https

方案:
由于nodejs自身没有对http连接的可配置的超时控制机制,需要自行增加

/**

  • if timeout, emit “timeout” event, abort request, and emit “abort” event for response

  • @param options

  • @param timeout

  • @param callback
    */
    function httpGetWithTimeoutSupport(options, timeout, callback) {
    var timeoutEvent;

    var req = http.get(options, function(res) {
    res.on(“end”, function() {
    clearTimeout(timeoutEvent);
    console.log(“end”);
    })
    res.on(“close”, function(e) {
    clearTimeout(timeoutEvent);
    console.log(“close”);
    })

     res.on("abort", function() {
         console.log("abort");
     });
    
     callback(res);
    

    });

    req.on(“timeout”, function() {
    console.log(“timeout received”);
    if (req.res) {
    req.res.emit(“abort”);
    }

     req.abort();
    

    });

    timeoutEvent = setTimeout(function() {
    req.emit(“timeout”);
    }, timeout);

    return req;
    }

httpGetWithTimeoutSupport(url.parse(“http://www.google.com”), 1000, function(res){
var data = “”;
res.on(“data”, function(d) {
data += d;
});
res.on(“end”, function() {
console.log(data);
})
});

nodejs自带一个默认的2分钟的强制超时, 见http.js;这个超时会导致close事件发生,错误代码为"timeout". 同时超时是针对连接而非单个的请求的(一个连接上有许多请求).