Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Timeout for http.createClient in Node.js?

There is a post: How do I set a timeout for client http connections in node.js

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

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.

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

like image 247
murvinlai Avatar asked May 25 '11 18:05

murvinlai


1 Answers

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.

like image 81
Raynos Avatar answered Sep 21 '22 19:09

Raynos