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

问题描述:

有个帖子:如何在 node.js 中为客户端 http 连接设置超时

但没有一个答案行得通.

but none of the answer will work.

所以,我有这样的代码:

So, I have the code like that:

    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 秒.如果是,则触发侦听器.

The biggest problem is that the url that I'm connection to may timeout. Therefore, I would like to set a timeout, like 15 secs. If so, trigger a listener.

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

However, I haven't seen any timeout features in the documentation for http.createClient. Please advise. Thanks. :)

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

您自己去柜台办理即可.

Just run the counter yourself.