bobbyrne01
bobbyrne01

Reputation: 6745

Setting socket based timeout on http request

The code below aborts the request if it takes longer than 10 seconds duration.

Is it possible to set a socket based timeout on the request using http module?

Also, should I be using a socket and request timeout?

var abortRequestError;
var timeout = 10000;
var requestObject = {
  host: 'xx.xx.xx.xx',
  path: '/api',
  port: 10000,
  method: 'GET'
};

var req = http.request(requestObject, function(res) {

  var responseBody = '';
  res.on('data', function(data) {
    responseBody += data;
  });

  res.on('end', function() {
    console.log(abortRequestError);
  });

}).on('error', function(error) {

  error = abortRequestError ? abortRequestError : error;
  console.log(error);

}).setTimeout(timeout, function() {

  abortRequestError = new Error('Request timed out');
  req.abort();
});

Upvotes: 0

Views: 1247

Answers (1)

Aleksei Zabrodskii
Aleksei Zabrodskii

Reputation: 2228

For connection timeouts, Node uses OS defaults. Simplified, these are triggered when you can't reach the server at all within a period of time.

After you established connection, request#setTimeout() function sets up idle timeout, which triggers when there have been no network activity for a period of time. Sounds like this is what you want. (Note that underneath it simply calls socket#setTimeout when socket is created, so there is no need to call both.)

For other kinds of logic, you'll need to set up your own thing with manual usage of timers. But the code you provided should work just fine for what you need — if, after being connected to, server stops sending data for longer than 10,000 milliseconds, timeout will trigger.

Upvotes: 1

Related Questions