node. js Event Loop

Source: Internet
Author: User
Tags emit readfile

node. js Event Loop

node. JS is a single-process single-threaded application, but because the V8 engine provides asynchronous execution callback interfaces, these interfaces can handle a lot of concurrency, so performance is very high.

node. js almost every API supports callback functions.

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:

Introduce the events module var events = require (' events ');//Create Eventemitter object var eventemitter = new events. Eventemitter ();//Create event handler var Connecthandler = function connected () {   console.log (' connection succeeded. ');     Trigger Data_received Event    eventemitter.emit (' data_received ');} Bind Connection Event handler Eventemitter.on (' Connection ', Connecthandler); Use the anonymous function to bind data_received event Eventemitter.on (' data_received ', function () {   console.log (' Data received successfully. ‘);});/ /Trigger Connection Event Eventemitter.emit (' Connection '); Console.log ("program execution is complete. ");

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:

Novice Tutorial Official website address:www.  Runoob.  COM    

Create the Main.js file with the following code:

var fs = require ("FS"); Fs.readfile (' Input.txt ', function (err, data) {   if (err) {      console.log (err.stack);      return;   }   Console.log (Data.tostring ());}); Console.log ("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:

Program execution complete  Rookie tutorial official website address:www.  Runoob.  COM     

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.

Excerpt from: http://www.runoob.com/nodejs/nodejs-event-loop.html

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.