-1

I'm trying to test out a HTTP request with the http npm module. if the request isn't sucessful it doesn't provide a response. I'm trying to make it so if there isn't a response in 3 seconds, it runs code such as console.log('didnt work').

What i have:

http.get({
    path: 'http://google.com'
}, function (response) {
    if (!response) {
        console.log('didnt work')
    } else {
        console.log('worked')
    }

});
austttn19
  • 73
  • 5
  • how is different from https://stackoverflow.com/questions/6214902/how-to-set-a-timeout-on-a-http-request-in-node – xdeepakv Mar 24 '20 at 04:30
  • Does this answer your question? [How to set a timeout on a http.request() in Node?](https://stackoverflow.com/questions/6214902/how-to-set-a-timeout-on-a-http-request-in-node) – xdeepakv Mar 24 '20 at 04:30

1 Answers1

0

First, keep in mind that an http request is an asynchronous operation and the results whether a response or a timeout are event driven. So, nothing here blocks until the response or timeout happens. Instead, you register callbacks or listeners for events and you response to those.

More specifically, you can use the timeout feature for http.get(). Doc here.

request.setTimeout(timeout[, callback])

timeout <number> Milliseconds before a request times out.

callback <Function> Optional function to be called when a timeout occurs.
                    Same as binding to the 'timeout' event.

Returns: <http.ClientRequest>

Once a socket is assigned to this request and is connected 
`socket.setTimeout()` will be called.

If it sees no response within the timeout time you set, then it will generate the timeout event, call the callback and close down the socket. You can use this as an event driven conclusion to the socket in the same way you might be waiting for the data event.

jfriend00
  • 683,504
  • 96
  • 985
  • 979