This article will help you grasp different concepts behind Node.js and will empower you to create production-ready applications.
Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
We have all read the above statement, but what does it really mean? Let us understand how traditional server models used to work.
In a traditional server model, for each request to the server, a thread is spawned to handle the same request. This type of implementation doesn’t scale much, as the number of multiple requests your server can handle is directly proportional to the number of threads your machine can spawn.
In Node, a process consists of one main thread of execution, and a myriad of background threads (typically performing I/O work). Coordination between the background threads and the main thread is performed using a queue. The main thread pulls tasks from the queue (enqueued in the order they were received) and executes them.
In short, some of the few benefits of using Node.js are listed below:
- Reduces development time.
- Reduces the number of servers needed/server cost.
- Reduces API response time/page load time.
But there are some cases where you shouldn’t use Node.js.
Before actually coding in Node.js, I would like to mention some of the core concepts of Javascript which allow Node.js to work the way it does.
1. Higher Order Functions
This might be a very common thing for any JS developer, but someone who is new to JS might find this weird. In JS, you can pass a function as a parameter to another function. Let us understand this with a simple example.
In the above example, the function sayWhat
was passed to speak
function.
2. Callbacks
In the above example we already saw callback
in use. The following statement halts the code execution.
alert(`${name} threw a boomerang few years ago`);
Once you close the alert, the method which was passed is being called. This is called a callback.
3. Event Loop
All the function calls are put into a call stack on LIFO basis. The event loop continuously checks the call stack to see if there’s any function that needs to run. While doing so, it adds any function call it finds to the call stack and executes each one in order.
Let us take a practical approach to understanding event loop. First run the code below.
The above code will work as expected. 3 → 1 → 2 → 4
The result for a minimum setTimeout
calls the function which is passed as a parameter after the time mentioned in the second parameter. As the time is mentioned as 0, you might think the output to be 3 → 1 → 2 → 4. But because of the way event loops work, it is actually 3 → 2→ 4 → 1.