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 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.

The event loop is a Node.js very central part of it, and many Node.js of its characteristics depend on it, and it has both positive and negative effects. For example, performance improvements in handling I/O intensive tasks and lack of sufficient information about the error stack. The Node.js asynchronous callback-driven programming paradigm is directly rooted in the existence of event loops.

Node.jsThere is an event loop in each of the processes. As long as the process exists, it exists and continuously dispatches the methods and operating system methods in your program. The event loop starts in an infinite loop, in the Node.js end of the function in the binary file, and main exits when there is no more event handler to execute. It runs in a single thread, and the event handlers are executed one after the other.

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:

Introduce the events module var events = require (' events ');//Create Eventemitter object var eventemitter = new events. Eventemitter ();//Create event handler: Connect var Connecthandler = function connected () {    console.log (' connection succeeded ');    Trigger Data_received Event    eventemitter.emit (' data_received ');} Create event handler: Receive data var Receivehandler = function received () {    console.log (' Data received successfully ');}
Monitor event Eventemitter.on (' Connection ', Connecthandler); Eventemitter.on (' data_received ', receivehandler);// Trigger Event Eventemitter.emit (' Connection '); Console.log (' Program execution Complete ');

The result of the execution is:

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.

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.