Categories
JavaScript Answers

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

Spread the love

To set a timeout on a http.request() in Node, we call request with an object with the timeout property.

For instance, we write

const options = {
  //...
  timeout: 3000,
};

const request = http.request(options, (response) => {
  // ...
});

request.on("timeout", () => {
  request.destroy();
});

to call request with the options object which has the timeout set to 3000 ms.

We get the response from the callback.

And we listen for the timeout event with on.

In the on callback, we call destroy to stop the request.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *