Before reading this article, I highly recommend reading the previous part:
1.
Introduction to NodeJS, A SSJS: Part I
In
Part I of Introduction to NodeJS, we discussed the main three components of NodeJS and how they are stacked to provide the best performance to the user. In this part II, we shall discuss the Event Loop architecture in NodeJS.
Before we dive into NodeJS's EventLoop, we will just provide a glance at the JavaScript EventLoop. It is better to understand the JavaScript's EventLoop to understand the NodeJs's EventLoop in a better way.
Some of you guys might be familiar with the JavaScript's EventLoop, but for those who are not, please follow this article from this point else skip this point and jump to the NodeJS EventLoop.
JavaScript EventLoopAs we know, JavaScript runs in a single thread. When the user requests an operation, the runtime provides a callback (to the operation that will be executed once the operation is done) and moves on to the next step to do some other operation.
- When an event occurs, the corresponding event message is queued into the EventLoop
- The Event Loop is checked for the message existence, if an event message exists then the corresponding callback is fired.
- Once the callback is done with the job, control is returned to the event loop that continues from Step 2.
Note: if the JavaScript runtime is engaged with the event message, then the other messages must wait until the current message is done with the job. Sometimes you might get the browser saying something like “Browser is not responding”. This is because of the long-running event message. So try to keep the event messages as short as possible.
For example:
- var msg = document.getElementById("msg");
- msg.addEventListener("click", function () {
- this.style.color = "blue";
- });
In this example above, we have attached the click event to the anonymous function as the event handler. When we clicked on that msg element, an event message is queued into the Event Queue.
If there are messages in the queue, then the click event message waits for the other messages to be done. All the other messages are processed, the over click event message is processed and the result is rendered into the DOM.
So we are somewhat clear about the JavaScript's Event Loop. Let us move onto the NodeJS EventLoop.
NodeJS EventLoop
As stated by Unknown, “Everything runs in parallel; except your code”. Yes, your code runs synchronously but the operations given by the code run by Node is asynchronous.
The preceding figure shows the event loop architecture of NodeJS.
- When a request arrives, it is queued up into the EventLoop with a JavaScript Closure that includes the event (request, response) and corresponding callback.
- The event is then given to the one worker thread if the job seems to take a long time to complete that is from a C++ Thread Pool, handled by the libuv library.
- Once the job is done, the corresponding callback is fired to return back the response to the Main thread.
- The Event Loop returns the response to the client.
For example:
- var fs = require('fs');
- fs.readFile('avator.png', function(avator) {
- console.log(‘image is loaded…’);
- });
- fs.writeFile('log.txt', 'Done', function() {
- console.log(‘Done !..’);
- });
The execution flow goes as in the following:
- Our code tells the node to do the two tasks read() and write() and then takes a rest.
- The read() and write() operations are enqueued into the Event Loop and distributed the job to the worker thread.
- Once the worker threads are done with the job, it will fire the callbacks to return the response to the Event Loop.
- Then the Event Loop returns the response to the client.
The callbacks of read() and write() will be executed in order to which one completes first. But note that only one of the callbacks would be executed at a time. So that the Node environment ensures that there won't be a deadlock or race condition. So it makes sure that the NodeJS provides Non-blocking IO.
We could consider the Post Office environment for the NodeJS.
When we post (request) something, the Post Master (Node) asks Post Men to deliver (get the job done) the post to the corresponding address.
Once the post men deliver the posts, they are reporting to the Post Master that it's completed, one by one.
Even the Post Master may assign some work to the post man at the time of reporting if he is free.
Conclusion
Finally, I am happy that I am able to explain for you the NodeJS's EventLoop. Please comment if you disagree on some points or are interested in learning more about the points explained. In my next part, we will discuss when to use and why to use NodeJS.
Thanks for Reading. Happy Coding.