node. js Event Loop
node. JS is a single-process single-threaded application, but it supports concurrency through events and callbacks, so performance is very high.
Each of the APIs for node. JS is asynchronous and runs as a standalone thread, using an asynchronous function call, and handling concurrency.
node. js basically all of the event mechanisms are implemented using the Observer pattern in design mode.
The node. JS single thread resembles an event loop that enters a while (true) until no event observer exits, and each asynchronous event generates an event watcher that invokes the callback function if an event occurs.
Event Driver
node. JS uses the event-driven model, when the Web server receives the request, shuts it down and processes it, and then goes to service the next Web request.
When this request is completed, it is put back into the processing queue, and when it arrives at the beginning of the queue, the result is returned to the user.
This model is very efficient and extensible because webserver always accepts requests without waiting for any read and write operations. (This is also known as non-blocking IO or event-driven IO)
In the event-driven model, a main loop is generated to listen for events and trigger a callback function when an event is detected.
The entire event-driven process is so simple. Somewhat like the Observer pattern, the event is equivalent to a subject (Subject), and all the processing functions registered to the event are equivalent to the Observer (Observer).
node. JS has multiple built-in events, and we can bind and listen to events by introducing the events module and instantiating the Eventemitter class, as in the following example:
//Introducing the Events modulevarEvents = require (' Events ');//Create a Eventemitter objectvarEventemitter =Newevents. Eventemitter ();//To create an event handlervarConnecthandler =functionconnected () {Console.log (' Connection succeeded. ‘); //Triggering data_received EventsEventemitter.emit (' data_received ');}//binding Connection Event handlersEventemitter.on (' Connection ', Connecthandler); //binding data_received events with anonymous functionsEventemitter.on (' data_received ',function() {Console.log (' Data received successfully. ‘);});//Triggering connection EventsEventemitter.emit (' Connection '); Console.log ("The program has finished executing. ");
Next let's execute the above code:
Node Main.js connection succeeded. Data received successfully. Execution of the program is complete.
How does the Node application work?
In the Node application, the function that performs the asynchronous operation takes the callback function as the last parameter, and the callback function receives the error object as the first argument.
node. js Event Loop