What is the event loop in node.js, As you might aware that Node.js is not scripting or programming language. It is an asynchronous event-driven JavaScript runtime. Node.js architecture design is almost similar to like Ruby’s Event Machine or Python’s Twisted. Nodejs starts executing the by entering into event loop when there is an input script. And exits from the event loop when there are no more callbacks to perform.
What is the event loop in node.js?
The event loop is the heart of Node.js that allows executing non-blocking I/O operations, in other words, asynchronous operations. Almost all modern kernels are multi-threaded, can execute multiple tasks in the background. The kernel informs Node.js when any of the tasks get completed. Then Node.js can add a callback to the poll queue that to be executed eventually.
How does event loop work?
As Node.js starts, it first initializes the event loop. As we can see in the below diagram, it has a set of phases.
And every phase has a FIFO queue of callbacks to execute. Every phase has special operations. When the event enters a given phase, operations with the corresponding phase will be executed.
The node.js is a cross-platform run time environment, it uses a lot of libraries and tools to perform non-blocking I/O operations. The list of dependencies that Node.js relies on to work the way it does.
- V8
- libuv
- http-parser
- c-ares
- OpenSSL
- zlib
- npm
- gyp
- gtest
Libuv is cross-platform and has a library that was originally written for Node.js. It is designed for the event-driven asynchronous I/O model. The library provides much more different I/O polling mechanisms. The I/O or event loop is the heart part of libuv. It establishes the content for all I/O operations, and it is meant to be tied to a single thread. One can perform multiple event loops as long as each runs in a different thread.
The event loop follows the rather usual single-threaded asynchronous I/O approach. All (network) I/O is performed on non-blocking sockets which are polled using the best mechanism available on the given platform. As part of a loop iteration, the loop will block waiting for I/O activity on sockets which have been added to the poller and callbacks will be fired indicating socket conditions (readable, writable hangup) so handles can read, write or perform the desired I/O operation.
In order to better understand how the event loop operates, the following diagram illustrates all stages of a loop iteration:
One thought on “What is the event loop in node.js?”
Comments are closed.