3

The code below is a simple Node.js web server that responds to a request when the URL is matched.

Researching online about node.js it is stated that once you start your script (node index.js) callbacks will be placed in their appropriate phase, then after your script is parsed the node process will enter the Event Loop and execute appropriate callbacks specific to a phase. Node will exit if there are no more callbacks to be executed.

So my question is if the request handler is run the first time when I visit the home page "/" OR Hello Page "/hello", how come node is still running even after subsequent requests.

const http = require('http');

const server = http.createServer((req,res) => {
  if(req.url === "/") {
    res.end("Home Page")
  }
  else if(req.url === "/hello") {
    res.end("Hello Page")
  }
  else {
    res.end("Page Not Found")
  }
})


server.listen(5000)

I expect that once the Request Handler is executed it should be removed from whichever Phase it has been put into, hence node should exit. So what is keeping the Node program from exiting?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
claOnline
  • 1,005
  • 3
  • 10
  • 18

1 Answers1

6

Node.js doesn't exit just because there is no pending work for the event loop. (This page is sadly misleading-through-being-incomplete in that regard.) It exits if:

  1. There is no pending work for the event loop, and
  2. There are no outstanding I/O requests, and
  3. There are no listening I/O server sockets

(I think that's a complete list. I can't find relevant documentation, though I remember reading something on their website about this years ago.)

If it exited when there was no pending work for the event loop, it wouldn't even wait to run your connection callback once. It would exit immediately after the listen call.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    it's probably also worth mentioning that there is more JavaScript than the actual application code shown here... the whole Node.js framework. – Brad Jun 02 '19 at 16:17