After a lot of digging, I understood how node.js internally works. This blog is based on my researches, stay patient to deep dive!😁

Okay! So let’s understand first what Node.js is 🐘. The documentation says: “Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.”

A lot of fancy words here 🤯. Let’s together break it down 💪 First thing first, what is runtime and why node.js is a runtime ???

A runtime is code/instructions executed specifically while your program is running, especially those instructions that you do not write explicitly, but are necessary for the proper execution of your code.

An engine is the actual code responsible to execute your program.It converts your code into machine code so that your computer(CPU) will execute it.

In JavaScript — The JavaScript engine translates your script into runnable machine code instructions so it can be executed by the CPU .

The JavaScript runtime environment provides your scripts with utility libraries which can be used during execution. It’s your script that references these libraries. The engine itself doesn’t depend on them.

The important thing is the JavaScript engine implementation is totally independent of the runtime environment. Engines aren’t developed with any particular environment in mind.

For example — The Chrome Browser and node.js use the same Engine — V8, but their Runtimes are different: in Chrome you have the window, DOM objects etc, while node gives you Buffers and processes.

Imagine a robot is cooking food:

  • Your code would be the instructions to the robot to cook food.
  • The engine would be the robot that can understand the instructions and act on it.
  • The runtime would be the LPG gas stove and the utensils.

Node.js is a runtime environment because it has V8 engine, libuv threadpool and OS Async Helpers. All of these gives you the power to write the JavaScript code on the server.

Coming to another fancy word: “V8 engine”🦋

The documentation says: “V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.”

Well, it means, V8 is a C++ program, which receives JavaScript code, compiles, and executes it.V8’s responsibilities:

  1. Compiles and executes JS code.
  2. Handling call stack to run your JS functions in some order
  3. Managing memory allocation for objects — the memory heap
  4. Garbage collection of objects which are no longer in use
  5. Provide all the data types, operators, objects and functions
  6. Provide the event loop, but this is sometimes implemented by the browser as well

Note:-V8 dosn’t know anything about the Document Object Model (DOM) — which is provided by the browser

Let’s understand threads and processes before understanding event loop.

Anything your computer does is done using a process. For example a file is opened by a text editor process. Music is played by a music player process.

Similarly, in order to run your node program, a process is required. This process is created as soon as you run node in your terminal.

Each process has threads which actually execute the code inside the program of the process. Threads use your CPU cores to execute the code. A process can have more than one thread.

So, when you run the following code using node: const mul= 4*2; — A process is created and threads are assigned to the process to execute the code.

NodeJS process is not “single-threaded”. “Event loop” is single-threaded

Event Loop

Consider the following code:

console.log("This is the first statement");

setTimeout(function(){
console.log("This is the second statement");
}, 5000);
console.log("This is the third statement");

Output

This is the first statement
This is the third statement
This is the second statement

Node.js doesn’t wait for 5 sec for the second statement, rather it executes the third statement and in parallel waits for the timer of 5 sec to expire despite of being single threaded. How? Event Loop to the rescue!

“Event loop” is, well, just a loop like a for loop or a while loop. When you start your node process by running node app.js, the following steps take place:

  1. V8 engine executes your code in app.js
  2. V8 engine immediately starts “Event Loop”

So one thing should be very much clear now — Event loop doesn’t execute your code , V8 engine is responsible or executing your code.

“Event Loop” is some piece of code in a loop which picks up tasks from“Job/Task Queue” and sends them to V8 to be executed.

Wait! Hold On! Which tasks and what is the “Job Queue”?

So a Job Queue is FIFO data-structure. The tasks which are pushed first will be picked up first by the Job Queue.

The tasks here is any code inside the function that needs to be executed. When I/O operation, setTimeout, setInterval, setImmediate, or an OS task completes, callback function is called, which is then entered inside the Job Queue.

As I mentioned above, event loop is like a for or while loop. It has certain phases through which it iterates — it is called “Event Loop Iteration”.

Each of the phases has its own queue/heap which is used by the event loop to push/store the callbacks to be executed (There is a misconception in Node.js that there is only a single global queue where the callbacks are queued for execution which is not true.).

#programming #javascript #node #web-development #developer

Handling Asynchronous Operations in Node.js
3.50 GEEK