How Node.js works in background - A brief analysis

Node.js uses only one JavaScript execution thread.

Question is − how Node.js process multiple http or any other requests and there can be question on performance, security as well?

  • Node.js starts event loop on application start and handles callback functions using it.Node.js maintains a worker pool. Long running operations are transferred to this worker pool and event pool only handles responses from this worker pool on completion of tasks.

  • Worker pool works with operating system to do the heavy lifting of work and managing scheduling of tasks.

  • Worker pool once finished task responds to event loop using callback functions.

  • Event loop maintains the order of execution for appropriate events.

Event loop

  • It first checks for any timer events like setTimeout or setInterval.

  • Second, it checks for pending callbacks e.g. I/O related callbacks pending to execute.

  • Next step is Poll; Node will try to find new I/O for executing their callback functions.

  • Check phase, in this phase node will execute callback functions immediately. It uses setImmediate call

  • Close callback − In the end node will do the close callback functions which are registered.

  • If there are no registered events remaining for execution then only node will do process.exit .

  • Node maintains a ref variable to hold the counter for events, on each new event the counter will get incremented.

  • In server environment, we create a server using createServer which does not have a close event so it won’t get closed automatically by node.js unless process is stopped by manually.

  • By default node mainatsn scopes for each http request to avoid it from being mixed with other requests.

  • The global objects defined if any can be accessed by any requests and that requires to be taken care by developer.