0

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();
});
3
  • Do you mean connection timeout? Commented Nov 10, 2016 at 20:31
  • It must only be considered broken if the data flow is interrupted for 10 seconds .. is that connection timeout? Commented Nov 10, 2016 at 20:34
  • Your code calls a correct function for what you want to achieve — timeout in socket being idle; perhaps the problem is elsewhere. What are you trying to achieve, what exactly doesn't work? Commented Nov 10, 2016 at 20:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.