o7planning

Understanding Event Loop in NodeJS

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- NodeJS Event Loop Overview

NodeJS is a Single Thread application, which operates on a platform written by C++. ​​​​​​​This platform uses multi-thread to carry out  tasks at the same time.
The following figure illustrates requests sent to the NodeJS server from the users side.
Each request from the users side is treated to be an event by the NodeJS. They is placed into an Event Queue. The NodeJS uses FIFO (First In First Out) principle, which means that the requests coming first will be handled first.
Event Loop
As an endless loop, it passes the requests to the thread Pool and each request is registered a Callback function.  When a request is finished handling, the corresponding Callback function will be called to be executed.
Thread Pool
Being a program by  C++ language, it supports multi threads. Therefore, herein, requests will be handled on different threads. The NodeJS also supports Multi Processes. This means that they can be executed on different cores.
When a request is finished handling. The NodeJS will call the Callback function (registered for this request) to execute it.
CONCLUSIONS:
First basic conclusion: If each connection to Server opens a Thread . It will take very much memory. This has been proven when you compare Apache and Nginx (two Web Servers deploying PHP applications). The Apache uses much more memory than the Nginx.
The NodeJS is similar to the Nginx in the fact that they use only a Single thread to receive connections from an user, and treat each request of the user as an event.
Second basic conclusion: I/O activities cost many resources of the system, therefore, the NodeJS manages use of I/O activities strictly.  So you need to use only Callback when you execute the duties related to I/O.
Basically, many things in the NodeJS are running  in parallel on different threads, but they are managed directly by the NodeJS, for example, Thread Pool. What you write is run on a single thread.

View more Tutorials:

Maybe you are interested

These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.