Wednesday, Oct 18, 2023
Zedan Saheer
How Node.js executes like a multi-thread?
Letβs discuss a little Backend?
But before that letβs understand the fundamentals alright?
What are these technical jargons which we usually hear?
What is Node.JS?
Node.js is a event-driven JavaScript runtime environment that achieves low latency and high movement of output by taking a Non-blocking approach to serving requests. In other words, Node.js wastes no time or resources on waiting for Input/Output requests to return.
It is built on Chromeβs V8 engine. This engine takes your JavaScript code and converts it into a faster machine code. Machine code is low-level code which the computer can run without needing to first interpret it. You can use TypeScript or CoffeeScript as well for Node.JS.
Non-Blocking Approach
Imagine there are two requests X and Y, in a blocking approach, X request is first resolved and then only moves to Y request which means Y has to wait till X request is resolved.
So basically in non-blocking approach you can send requests to both X and Y before resolving X, this means almost parallely you are able to send requests. making it faster!
But JavaScript is a single threaded language is what some of you might probably be thinking? Well this non-blocking I/O eliminates the need for multi-threading since the server can handle multiple requests at the same time.
Okay, you have got an idea now but still feeling kind of lost because we have one more part to discuss.
What do I mean by Event-driven
?
Node.js makes extensive use of events which is one of the reasons behind its speed, It is used to synchronize the occurrence of multiple events and to make the program as simple as possible.
-
There are callback functions called event-handlers which is called when an event is triggered.
-
An event loop that listens for event triggers and calls the corresponding event handles for that event.
-
The functions which listens for a trigger is called an observer.
There are two types of Events :
-
πΊπππππ π¬πππππ : C++ core from a library called libuv.
-
πͺπππππ π¬πππππ : JavaScript core.
Comibining these functions and ideas we can create an Event-Driven Non-Blocking program that acts fast like a multi-threaded output.