Event Loop

Due to the single-threaded design of Node.js, it is considered to be one of the most complicated architectures. Being completely event-driven, understanding Event Loop is key to mastering Node.js. Node.js is designed as an event-based platform, meaning anything that occurs in Node.js is just a reaction to an event. Any operation done in Node.js passes through a series of callbacks. The complete logic is abstracted from developers and is handled by a library called libuv. We will gain a thorough understanding of the Event Loop in this section including how it works, common misconceptions, its various phases, and more.
The following are some of the common myths about Event Loop and a brief on the actual workings:

  • Myth#1—Event Loop works in a different thread than the use code: There are two threads maintained, one parent thread where the user-related code or user-related operations run, and another where the event looping code runs. Any time  an operation is executed, the parent thread passes over the work to the child thread, and once the child thread operation is completed, it pings the main thread to execute the callback:
  • Fact: Node.js is single-threaded and everything runs inside the single thread. Event Loop maintains the execution of the callback.
  • Myth#2—Thread pool handles asynchronous events: All asynchronous operations, such as callbacks to data returned by a database, reading filestream data, and WebSockets streams, are off loaded from a thread pool maintained by libuv:
  • Fact: The libuv library indeed creates a thread pool with four threads to pass on the asynchronous work, but today's operating systems already provide such interfaces. So as a golden rule, libuv will use those asynchronous interfaces rather than the thread pool. The thread pool will only be used as the last alternative.
  • Myth#3—Event Loop, like a CPU, maintains a stack or queue of operations: The Event Loop goes through a maintained queue of asynchronous tasks maintained via the FIFO rule, and executes the defined callbacks maintained in a queue:
  • Fact: While there are queue-like structures involved in libuv, the callbacks are not processed through a stack. The Event Loop is more of a phase executioner with tasks processed in a round-robin manner.