httpnode.jstimeout

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


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

Any hints?


Solution

  • Just to clarify the answer above:

    Now it is possible to use timeout option and the corresponding request event:

    // set the desired timeout in options
    const options = {
        //...
        timeout: 3000,
    };
    
    // create a request
    const request = http.request(options, response => {
        // your callback here
    });
    
    // use its "timeout" event to abort the request
    request.on('timeout', () => {
        request.destroy();
    });
    

    See the docs: enter image description here