5

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. :)

Community
  • 1
  • 1
murvinlai
  • 48,919
  • 52
  • 129
  • 177
  • See answers in this duplicate question: http://stackoverflow.com/questions/6214902/how-to-set-a-timeout-on-a-http-request-in-node (especially see douwe's answer) – Sandman4 Mar 05 '13 at 10:55

1 Answers1

6
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.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • @murvinlal slightly less efficient then using the native timeouts but not noticeably slower, should be fine for efficiency. – Raynos May 26 '11 at 00:17
  • https://github.com/mikeal/request/issues/25 - this library is built on top of http/client so it sounds like its not really a feature in nodes core http client -- agree with Raynos – Josh May 26 '11 at 05:34
  • Thanks. I also have a question. for the code, it set the timeout for the request. Do I need to set another timeout handler for response? e.g response.addListener('data', ... ); and add one like that: response.on('data-timeout', ...); – murvinlai May 26 '11 at 18:04