How to set a timeout on a http.request() in Node?

3,128 views
Skip to first unread message

Claudio Cicali

unread,
Jun 2, 2011, 1:21:46 PM6/2/11
to nod...@googlegroups.com
Sorry, this is a xpost iwth Stackoverflow, but I still have not found an answet to this (apparently) simple question:

I'm trying to set a timeout on an HTTP client that uses http.request with no luck. So far what I did is this:

    var options = { ... }
    var req = http.request(options, function(res) {
      // Usual stuff: on(data), on(end), chunks, etc...
    }

    /* This does not work TOO MUCH... sometimes the socket is not ready (undefined) expecially on rapid sequences of requests */
    req.socket.setTimeout(myTimeout); 
    req.socket.on('timeout', function() {
      req.abort();
    });

    req.write('something');
    req.end();

Btw, this tecnique works fine: http://stackoverflow.com/questions/6129240/how-to-set-timeout-for-http-createclient-in-node-js

If I use the socket timeout, and I issue two requests one after another (without waiting the first to finish), the second request has the socket undefined (at least at the moment I try to set the timeout).. maybe there should be something like on("ready") on the socket...

Any hints?

mscdex

unread,
Jun 2, 2011, 2:32:55 PM6/2/11
to nodejs
On Jun 2, 1:21 pm, Claudio Cicali <claudio.cic...@gmail.com> wrote:
> Sorry, this is a xpost iwth Stackoverflow, but I still have not found an
> answet to this (apparently) simple question:
>
> I'm trying to set a timeout on an HTTP client that uses http.request with no
> luck. So far what I did is this:

AFAIK, you can't set a timeout with the current (0.4) API because of
the way http(s) Agents are currently implemented. IIRC the request
should eventually timeout after 2 minutes and an 'error' event will be
emitted on the request object.

Claudio Cicali

unread,
Jun 2, 2011, 2:51:43 PM6/2/11
to nod...@googlegroups.com
Yes, indeed... 2 minutes is the current timeout. So if we need a smaller timeout we can use the "applicative" approach as in http://stackoverflow.com/questions/6129240/how-to-set-timeout-for-http-createclient-in-node-js


mscdex

unread,
Jun 2, 2011, 5:55:59 PM6/2/11
to nodejs
On Jun 2, 2:51 pm, Claudio Cicali <claudio.cic...@gmail.com> wrote:
> Yes, indeed... 2 minutes is the current timeout. So if we need a smaller
> timeout we can use the "applicative" approach as inhttp://stackoverflow.com/questions/6129240/how-to-set-timeout-for-htt...

Well, that's more like using the deprecated http API :)

Claudio Cicali

unread,
Jun 3, 2011, 1:08:41 PM6/3/11
to nod...@googlegroups.com
Yeah, maybe, but as for now this seems the only working approach. If you try to set the timeout on the socket, you'll get an undefined socket on the next *immediate* call to a request creation.
Reply all
Reply to author
Forward
0 new messages