node. js Event Loop

Source: Internet
Author: User
Tags emit readfile

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 Module  var=require(' events ');  Create Eventemitter object var=New events.  Eventemitter();             

The following program binds event handlers:

Handler Eventemitter for binding events and Events .  On(' eventName ', eventHandler);       

We can trigger events through the program:

Trigger event Eventemitter.  Emit(' eventName ');     
Instance

Create the Main.js file, as shown in the following code:

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); //use anonymous function bindings data_received events eventemitteron ( ' data_received ' , Span class= "KWD" >function () { Console. Log (//trigger connection event eventemitter.emit ( ' connection ' . Log ( "program completed. "                

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.

Let's take a look at the previous example and create a input.txt with the following file contents:

node. JS uses the event-driven model.

Create the Main.js file with the following code:

VarFs= Require("FS");Fs.ReadFile(' Input.txt ', function (Err,Data) { if  ( Err Console. Log (err. Stack return;} Console. (data. Tostringconsole. "program execution complete"          

The above program Fs.readfile () is an asynchronous function used to read the file. If an error occurs during the reading of the file, the error Err object will output an error message.

If no error occurs, ReadFile skips the output of the Err object, and the contents of the file are output through the callback function.

Execute the above code and execute the result as follows:

After the program executes, node. JS uses the event-driven model.

Next we delete the Input.txt file, and the execution results are as follows:

Program execution complete  Error: ENOENT,' input.txt '    

The error message is output because the file input.txt does not exist.

node. js Event Loop

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.