Node.js is a server side java script framework. It is a single-threaded application, but it can support concurrency via the concept of event and callbacks. The event loop is what allows Node.js to perform non-blocking I/O operations, and this is what i am going to discuss in details.

What is event loop in Node.js :-

Node.js is pretty fast compared to other similar technologies, because it uses events heavily. Basically, as soon as Node server starts its wait for an events to occur and  responds accordingly.

In an event-driven application, there is generally a main loop that listens for events and then triggers a callback function when one of those events is detected.

Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through the events module and EventEmitter class,  which are used to bind events and event-listeners.

The following diagram shows a simplified overview of the event loop’s order of operations.

 

 

 

 

 

 

 

 

 

 

 

 

  • timers:  This  phase executes callbacks scheduled by setTimeout() and setInterval().
  • pending callbacks:  Executes I/O callbacks deferred to the next loop iteration.
  • idle, prepare:  Only used internally.
  • poll:  Retrieve new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and setImmediate()), node will block here when appropriate.
  • check:  setImmediate() callbacks are invoked here.
  • close callbacks:  some close callbacks, e.g. socket.on('close', ...).

 

Between each run of the event loop, Node.js checks if it is waiting for any asynchronous I/O or timers and shuts down cleanly if there are not any.

I hope you will find this blog useful. Please comments to make it even more better.