如何在Node.js中为http.createClient设置超时?

如何在Node.js中为http.createClient设置超时?,node.js,timeout,Node.js,Timeout,有一个帖子: 但所有答案都行不通 我有这样的代码: var remote_client = http.createClient(myPost, myHost); var path = '/getData?'; var param = { }; var request = remote_client.request("POST", path,); // error case remote_client.addListener('err

有一个帖子:

但所有答案都行不通

我有这样的代码:

    var remote_client = http.createClient(myPost, myHost);
    var path = '/getData?';
    var param = {       };

    var request = remote_client.request("POST", path,);

    // error case
    remote_client.addListener('error', function(connectionException){
        console.log("Nucleus Error: " + connectionException);
        next(connectionException);
    });

    request.addListener('response', function (response) {
        response.setEncoding('utf-8'); 
        var body = '';

        response.addListener('data', function (chunk) {

        // get the result!              
        });
    });

    request.end();
最大的问题是我连接的url可能会超时。因此,我想设置一个超时,比如15秒。如果是,则触发侦听器

但是,我在http.createClient的文档中没有看到任何超时功能。请告知。谢谢。:)


只需自己运行计数器。

@Murvinal的效率比使用本机超时稍微低一些,但不会明显慢一些,这对于效率应该是很好的。-这个库是建立在http/client之上的,所以听起来它并不是核心http客户端中的一个功能——同意Raynoshanks的说法。我还有一个问题。对于代码,它设置请求的超时。是否需要为响应设置另一个超时处理程序?e、 g response.addListener('data',…);然后添加这样一个:response.on('data-timeout',…);请参阅此重复问题中的答案:(尤其请参阅douwe的答案)
var foo = setTimeout(function() {
    request.emit("timeout-foo");
}, 15000);

// listen to timeout
request.on("timeout-foo", function() { });

request.addListener('response', function (response) {
    // bla
    // clear counter
    clearTimeout(foo);
});