Search code examples
javascriptnode.jsnpm-request

How do you set a callback on timeout for the node.js request library?


With node's http library this would look something like

var request = http.request(options);
request.setTimeout(milliseconds, callback);

However, I'm using the wrapper library request and don't see a way to add a callback on timeout.

I'm creating an API endpoint to make an http request and expose that data, and I would like to be able to render a null result if the request times out.


Solution

  • There is no specific timeout callback. It will be called back as an error; then you have to distinguish it from other errors.

    request({
      timeout: 2000,
      url: 'http://timeout.example.org/'
    }).on('error', function(err) {
      if (err.code === 'ETIMEDOUT') {
        console.log("Timeout!");
      }
    });