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.