This blog provides the basic introduction of Nodejs with some of its major features and also the detailed description of Blocking, Non-Blocking, Asynchronous Operations, and Callbacks-
Node.js is an open source framework that has a huge fan following. The Nodejs community is quite active and have contributed a lot to add new capabilities in its long-list of features.
Also Check- Hydra Microservice Library in Node.js
Now, we will understand Blocking and Non-blocking in node.js-
Let’s take another example here –
As you can see in the above image, task1 internally calls getAllUsers which sends a request to the database to fetch all the users. The task2 internally calls getAllServices which makes an HTTP request to get all the services of some third party through their API.
Here, the task2() blocks until task1() returns because a single thread can execute only one thing at a time.
Now, you must know how node.js can convert the blocking calls into non-blocking execution.
Most of the System kernels are multi-threaded, and thus, can handle multiple requests and execute operations in the background concurrently. When one of these operations’ execution completes, the kernel informs to node.js and then the callback may be added to the queue to be executed.
So, here we convert the blocking code into the non-blocking code using callbacks.
In the above code, functions getAllUsers and getAllServices take callbacks. Node.js uses this callback mechanism when the kernel finishes with the I/O operations.
Now, you must understand that node.js is able to make asynchronous calls for non-blocking operations using the callback mechanism.
It makes NodeJS very fast and efficient, one of the reason in Nodejs that no function directly performs I/O. So, the process never blocks. Using callbacks in these asynchronous calls allows you to have as many I/O operations as your OS can handle, happening simultaneously.
Let’s take an example of Synchronous & Asynchronous modes using file system-
In the Synchronous version, if an error has occurred then it must have to be caught else, the process will be crashed.
In the asynchronous version, the developer is responsible for choosing the way of error handling. We should always use non-blocking variant over the blocking one.
The node.js web applications load faster as compared to the other frameworks. It provides several benefits to the developers which is basically the actual reason why some of the best companies around the world use node.js for their projects.
For more interesting blogs, subscribe to our Medium page here.
Reach out to us if you want to discuss your Node.js project, we assure you will find our work beyond satisfactory.