Importance of Event Loop in Node JS
Event Loop is at the heart of asynchronous non-blocking IO in Node JS. In this blog, we will discuss on Importance of Event Loop in Node JS.
First of all, let’s understand sync and async operations
- Synchronous or Blocking Operations
These are known as the async programming model. Synchronous behavior of any program means the first task in a program must finish processing before moving on to executing the next task.
For example: You go to X restaurant and place an order for food. You are told that you need to wait until the order is prepared. You are stuck or blocked at the counter until the order is served to you. This is called as synchronous or blocking behavior.
- Asynchronous or Non-blocking Operations
These are known as the async programming model. In his model, a second task can begin executing in parallel, without waiting for an earlier task to finish
For example: You go to Y restaurant and place an order for food. You have been given a buzzer that will notify you once your order is ready. In this case, you can perform other tasks or you have more freedom while you wait for an order. So, you are not blocked at the counter until the order is served to you. This is called asynchronous or non-blocking behavior.
For Free Demo classes Call: 02071173035
Registration Link: Click Here!
Why is event-loop in Node JS so important?
It tells you about how Node.js can be asynchronous and have non-blocking I/O, and so it explains the very important Node JS feature that made it popular and successful.
Do you know that that Node JS is single-threaded? It means Node JS cannot open a new thread and start to execute the code of the two requests in parallel. It waits or alternatively, it puts the event request in a queue, and as soon as the previous request is completed it dequeues the next one. Being single-threaded is Node JS’s limitation but that’s actually very helpful, as it simplifies a lot how you program without worrying about concurrency issues.
You might be wondering what exactly is an Event Loop.
An event loop is a loop that waits for events and then reacts to those events.
It is a result of event-driven programming, which is application flow control based on events or state changes. In JavaScript, this is implemented using a central mechanism that listens for events and calls a callback function associated with it, whenever such an event is triggered
It is an event listener that functions inside the NodeJS environment and is always ready to listen, process, and output for an event. An event can be anything from a mouse click to a key press or a timeout.
When Node.js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.
Actually, the task of the Node engine is to get an event from the queue, execute it as soon as possible, and get another task. Every task that requires an external resource is asynchronous, which means that Node puts the callback function on the event queue. Become a Full Stack Pro with SevenMentor! Join the Best Full Stack Course in Pune. Master Frontend and Backend Development for a Rewarding Tech Career. Enroll Now
Let’s understand this concept using the below example:
var http = require(‘http’)
var fs = require(‘fs’)
var server = http.createServer((request, response) => { response.writeHead(200, {‘Content-Type’: ‘text/html’}); fs.readFile(‘index.html’, (err, data) => {
response.end(data);
})
})
server.listen(4000)
In the above example, when the server receives the request, index.html “data” must be read from the filesystem. The readFile function which is an async function receives a callback with two parameters that will be called when the “data” is actually read.
This means that the event “the data is ready to be served” remains in a queue while the execution continues. So, even if the data in index.html is in large amounts and needs time to be read, other requests can be served because of the non-blocking nature of IO in Node JS.
When the file is ready, the callback will be extracted from the queue and the code (in this case the function response. end(data)) will be executed.
For Free Demo classes Call: 02071173035
Registration Link: Full Stack Training in Pune!
Event Loop allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.
There are two main use cases for event loop:
- High-Performance Servers
These servers use event loops to handle queries more efficiently.
- GUI applications
These use an event loop to respond to user input. Programs that run indefinitely such as UI applications, video games, web servers, etc. will have some form of an event loop. They can come in different flavors such as being a polling loop (check if there is an event every time it loops) or it can be handled via blocks and something triggers it to come and do its job.
For instance, imagine you have a program running a UI. If it’s idle and you look at your running processes it’s likely not going to be eating up a ton of processing time by continually looping. It can either be utterly silent or it may be taking up a fraction of a percent of the CPU’s time. But if you go and hit a button the program is going to wake up and do something. This is run by an event loop. Clicking that button fired an event which got processed by the event loop which called the buttons onClick event handler.
Almost all of the I/O primitives in JavaScript are non-blocking such as network requests, filesystem operations, and so on. Being blocking is the exception, and this is why JavaScript is based so much on callbacks, and more recently on promises and async/await.
Must watch our video on Demand For Full Stack Developers in Future
The event loop is the thing that continues to evaluate the queue in the search for new events to execute. Hence the fact that Node is a single thread simplifies a lot of the development, and the nonblocking I/O resolves the performance issues. It has various implications for how we write our code. The first and most important is that our code needs to be as fast as possible to free the engine so that other events can be served quickly.
Author:-
Dharamraj Pawale
Call the Trainer and Book your free demo Class For Full Stack Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.