Event Loop in Node.js

Node.js is a single thread application, but it supports concurrent processing through event definitions and callbacks. As all Node.js APIs are asynchronous and single threaded, it uses the async function to maintain concurrency. Node.js uses the Pattern Observer. The threads in Node.js hold an Event Loop and whenever any task completes, it will trigger the corresponding event to alert the Event Listener to be ready .

Event Driven programming in Node.js

Node.js uses a lot of events, which is why Node.js is quite fast compared to other technology products. As soon as the node starts its server, it will quickly initialize variables, declare functions, and then simply wait for events to occur.

In the event handler application, the main loop generally listens to events, and then triggers the callback function when one of the events is detected.

Event Loop in Node.js Picture 1

While events are quite similar to callback functions. The difference is that the callback function calls when a function is out of sync and returns its result while the event handler works on the Pattern Observer. This function will listen to events, acting as an Observers. Whenever an event arises, its Listener functions will start executing. Node.js has many events available through events Module and EventEmitter class can rely on bind events and listen to events.

Before using the event module, you use the require () method to declare the following:

 // Khai bao events module var events = require ( 'events' ); // Tao mot doi tuong eventEmitter var eventEmitter = new events . EventEmitter (); 

Then, to bind the Event Handler to an event, use the following syntax:

 // Gan ket event voi Event Handler nhu sau: eventEmitter . on ( 'eventName' , eventHandler ); 

You can activate an event using the emit () method of EventEmitter:

 // Kich hoat mot event eventEmitter . emit ( 'eventName' ); 

Example of Event Loop in Node.js

Create a js file named main.js with the following code:

 // Declare events module var events = require ( 'events' ); // Create a doi event eventEmitter var eventEmitter = new events . EventEmitter (); // Create an Event Handler: var connectHandler = function connected () { console . log ( 'I want to talk to you!' ); // Call for data_received eventEmitter . emit ( 'data_received' ); } // Gan's connection with Event Handler eventEmitter . on ( 'connection' , connectHandler ); // Get the data_received version of an eventEmitter . on ( 'data_received' , function () { console . log ( 'Please read the link.' ); }); // Click the connection eventEmitter . emit ( 'connection' ); console . log ( "Ket process." ); 

Run the above program as follows:

 $ node main . js 

The result is:

 I don't know what to do! 
Travel to find the best.
Let's get married.

How Node.js application works

In the Node.js application, an asynchronous function accepts a callback as the last parameter and the callback function accepts the error as the first parameter. Let's review the previous example. Create a text file named input.txt with the following content:

 QTM la trang Web huong dan cac bai lap trinh hoan toan mien phi cho tat ca moi nguoi !!!!! 

In this example, I use fs Module to handle File I / O operations (I'll cover in the next chapter). First, create a js file named main.js as follows:

 var fs = require ( "fs" ); fs . readFile ( 'input.txt' , function ( err , data ) { if ( err ) { console . log ( err . stack ); return ; } console . log ( data . toString ()); }); console . log ( "Ket process" ); 

Here, fs.readFile () is an asynchronous function for the purpose of reading files. If there is an error while reading the file, the err object will contain the error, otherwise the data will contain the contents of the file. The readFile function transmits err and data to the callback function after the file reading process has completed, and finally prints the content.

 Let's get married 
QTM is a Web page that contains all the scripts
Welcome to the world !!!!!!

According to Tutorialspoint

Previous article: Concept of Callbacks in Node.js

The following article: Event Emitter in Node.js

4 ★ | 1 Vote

May be interested

  • How to Fix Boot Loop Problems in WindowsHow to Fix Boot Loop Problems in Windows
    after starting your windows device, you may sometimes experience an infinite boot loop issue (also known as an 'infinite boot loop' error).
  • While loop in PythonWhile loop in Python
    what does the while loop in python do? what is the syntax and how to use while loop? those are the content we will approach in this python lesson.
  • What is Loop mail?What is Loop mail?
    what is loop mail? to help you with this question, the following article will help you find out what loop mail is.
  • For ... loop in JavaScriptFor ... loop in JavaScript
    the for ... in loop is used to iterate over the properties of an object. when we haven't discussed the object yet, you may not feel comfortable with this loop. but once you understand how objects work in javascript, you will find this loop very useful.
  • Loop control in JavaScriptLoop control in JavaScript
    javascript provides high control to handle loop commands and switch commands. there may be a situation when you need to exit the loop without having to go to its endpoint. there may also be situations when you want to jump over a part of the code block and start the next loop.
  • Why Microsoft Loop Can't Compare to NotionWhy Microsoft Loop Can't Compare to Notion
    many people have been using notion for brainstorming for years, so it's interesting to see if loop can replace it as they move deeper into the microsoft ecosystem.
  • How to fix 'Please Wait for the GPSVC' loop errorHow to fix 'Please Wait for the GPSVC' loop error
    the please wait for the gpsvc loop error in windows is an annoying problem that can cause the system to get stuck at shutdown. this loop is related to group policy client service (gpsvc).
  • The while loop in ShellThe while loop in Shell
    the while loop gives you the ability to execute a set of repetitive commands until certain conditions occur. it is often used when you need to manipulate iterative variable values.
  • Until loop in ShellUntil loop in Shell
    the while loop is perfect for the situation where you want to execute a set of commands while some conditions are true. sometimes you need to execute a set of commands until a condition is true, then you need to use a until loop.
  • Select loop in ShellSelect loop in Shell
    the select loop provides an easy way to create a numbered menu from which the user can select. it is useful when you want to ask the user to select one or more items from a list of options.