Originally published by Piero Borrelli at blog.logrocket.com
Whenever I hear people talking about Node.js, many questions arise about what it is exactly, what this technology is good for, and whether there is a future for it.
Let’s try to address the first part. The easiest way for me to answer such a question would be by listing out many definitions of what Node technically is:
But still, all these answers aren’t satisfying for me; there’s something missing. After reading the bullet points above, you might think of Node.js as just another JavaScript technology, yet the most important part of understanding it is by analyzing how it can be asynchronous and have a non-blocking I/O system altogether.
That is really what mutated it into a must-have for every web developer out there.
Understanding exactly how Node works behind the scenes will not only generate a greater knowledge of this technology, but it will also create traction for the people out there who haven’t used it to actually dive in and start learning it.
And for all the people out there who are already professionals in this field, understanding the in and outs of it will turn you into a new, up-to-date developer fully equipped to enhance its performance based on your needs.
So, in order to excavate into the world of Node, we will examine its core part: the event loop, which, in fact, is the part responsible for its non-blocking I/O model.
Before diving deep into the event loop, I would like to spend some time on threads. If you are wondering why this is necessary, I will tell you that in order to better understand a concept, we must first start to form a vocabulary in our minds that will help us to recognize each part of a system. This will eventually be of great advantage when later reading about the event loop, how it works, and how the concept of a thread applies to it.
Whenever we run a program, we create an instance of it, and, associated with that instance, we have something internal called threads. A thread can be seen as a unit of operations that our CPU has to perform for us. Many different threads can be associated with a single process of a program. Here is a graphic to help you form this idea in your mind:
A simple graphic on threads.
The most important piece to understand when talking about threads is: How can our machine determine which thread to process at any given moment in time?
As we know, our machines have a limited amount of resources (CPU, RAM), so it’s very important to correctly determine where we are going to allocate them or, better, which operations take precedence over others. And this all has to happen while still ensuring that no one operation takes too much time — nobody likes a slow laptop.
The mechanism used to solve the allocation problem is called scheduling, and it’s managed by our operating system by an entity called the OS scheduler. The logic behind this can be very complex, but to make a long story short, we can group two of the biggest ways in which this operation is performed:
How multi-core machines process threads.
Now that we have got a healthy refresh on how threads work, we can finally tackle the Node.js event loop logic. By reading this, you will understand the reason behind the previous explanation, and every piece will go at the right spot by itself.
Whenever we run a Node program, a thread is automatically created. This thread is the only place where our entire codebase is going to be executed. Inside of it, something called the event loop is generated. The role of this loop is to schedule which operations our only thread should be performing at any given point in time.
Please note: the event loop doesn’t get generated instantly as soon as we run our program. In fact, it only runs once the whole program has been executed.
Let’s now try to simulate how the event loop works and what it does to make our program work. To do this, I’m going to pretend that I’m feeding Node with a file called myProgram
and then get into the details of what the event loop will do with it.
In particular, I’m going to first write a brief little graphical explanation of what is happening during any event loop tick, and then I’m going to explore these phases in a deeper way.
A graphical explanation of the event loop.
performChecks
I shouldn’t need to tell you the event loop is, in fact, a loop. This means it has a specific condition that will determine if the loop needs to iterate again or not. Every iteration of the event loop is called a tick.
Whenever we execute our program, we will have a series of operations that need to be performed. These operations can be split into three main types:
setTimeout()
, setInterval()
, setImmediate()
)We will go into more details on these later; for now, let’s just remember that whenever one of these operations is pending, the event loop will perform a new tick.
For every loop iteration, we can distinguish the following phases:
setTimeout()
and setInterval()
are ready to be called in case of an expired timer.setImmediate()
function are ready to be called.This is a very common misconception about this technology. Node runs on a single thread, but some of the functions included in the Node.js standard library do not (the fs
module functions, for example ); their logic runs outside of the Node.js single thread. This is done in order to preserve our programs’ speed and performance.
When using Node.js, a special library module called libuv is used to perform async operations. This library is also used, together with the back logic of Node, to manage a special thread pool called the libuv thread pool.
This thread pool is composed of four threads used to delegate operations that are too heavy for the event loop. The above-mentioned long-running tasks in the event loop logic represent those operations described here as too expensive for the event loop.
In that sense, while some stack-like structures are involved in the above-mentioned process, a more precise answer would be that the event loop is composed of a series of phases, each with its own specific tasks, all processed in a circular repetitive way. For more info about the event loop’s exact structure.
Understanding the event loop is a vital part of using Node.js, whether you are trying to get more insights about this technology, learn how to improve its performance, or find a new, interesting reason to learn a new tool.
This guide should have helped you in exploring this subject. Feel free to leave a comment down below, opinions and feedbacks are extremely useful to help everybody to learn better.
Originally published by Piero Borrelli at blog.logrocket.com
=============================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter
Learn More
☞ The Complete Node.js Developer Course (3rd Edition)
☞ Angular & NodeJS - The MEAN Stack Guide
☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)
☞ Docker for Node.js Projects From a Docker Captain
☞ Intro To MySQL With Node.js - Learn To Use MySQL with Node!
☞ Node.js Absolute Beginners Guide - Learn Node From Scratch
☞ React Node FullStack - Social Network from Scratch to Deploy
☞ Selenium WebDriver - JavaScript nodeJS webdriver IO & more!
☞ Complete Next.js with React & Node - Beautiful Portfolio App
☞ Build a Blockchain & Cryptocurrency | Full-Stack Edition
#javascript #node-js #web-development