Is there an node.js http equivalent for XMLHttpRequest.readyState?

With Javascript’s XMLHttpRequest object, there is a property called readyState that is very often used in tandem with the response codes to check if an HTTP request has finished before processing other code.

 if (this.readyState == 4 && this.status == 200) {
   // Do stuff
 }

With Node.js’s http module you can make HTTP requests and retrieve status codes, just like the XMLHttpRequest object.

if (`${res.statusCode}` == 200) {
  //Do things
}

However, does the http module have any equivalent of the “readyState” property that the XMLHttpRequest object has? I can’t seem to find any documentation for it anywhere, but I want to make sure that I am only running the next code after the sent request has fully finished and not when it’s half-done.

Answer

You can use res.on('end', callback) to run whenever the response is fully completed, passing a callback to handle the response when completed.

In this case, take an example of a huge image. It proceeds to the end when all the chunks are retrieved and then, right after it, the callback is called.

const http = require('http')
const options = {
     host: 'placekitten.com',
     path: '/5000/2500'
} 

http.get(options, (res) => {
     let code = res.statusCode
     console.log("Got response: " + code)
     res.on('data', chunk => console.log("Data received"))
     res.on('end', () => {
          if (code === 200) {
               console.log("Sent request has fully finished")
          } else {
               console.log("Code wasn't 200!")
          }
     })
}).on('error', function(e) {
     console.log("Got error: " + e.message)
})     

Place this code here to try on a live server.