Node. JS Event Polling (1)

Source: Internet
Author: User
Tags readfile

Event polling (reference)

Event polling is the core content of node. A system (or a program) must contain at least one large loop structure (what I call a "pump"), which is a prerequisite for sustaining the system's continuous operation. The same structure is included in Nodejs, which we call "event polling", which exists in the main thread and is responsible for constantly invoking code written by the developer. We can check the instructions on Nodejs on the official website of Nodejs:

Node is similar on design to and influenced by systems like Ruby's Event machine or Python s Twisted. Node takes the event model a bit further, it presents the event loop as a language construct instead of as a library. In other systems there are always a blocking call to start the Event-loop. Typically one defines behavior through callbacks at the beginning of a script and at the end starts a server through a blo cking call like Eventmachine::run () . In Node there are no such start-the-event-loop call. Node simply enters the event loop after executing the input script. Node exits the event loop when there is no more callbacks to perform. This behavior was like browser JavaScript--the event loop was hidden from the user.

node is designed to resemble Ruby's event machine or Python's twisted system and is affected by it. Node further uses the event model, which renders the event loop as a language construct rather than a library. in other systems, there is always a blocking call to start the event loop. Typically, the behavior is defined by a callback at the beginning of the script, and finally the server is started by blocking calls such as Eventmachine: Run ()). There is no such start-event loop call in node. Node simply enters the event loop after executing the input script. When there are no more callbacks to execute, node exits the event loop . This behavior is like browser JavaScript-the event loop is hidden from the user.

As you can see, other languages call the event loop when there is a blockage, and node enters the event loop when it enters the script.

As we can see, this "looping" structure in Nodejs is not visible to the developer. (Borrow someone else's picture)

As shown, after each asynchronous function execution ends, an event is appended to the event queue (with the necessary parameters saved) (this includes the following 1.node how to tell that this asynchronous program is running out of 2. After execution, how to put into the event queue )。 The event polls the next loop to fetch the event, and then invokes the callback function (parameter,Q: How does this callback function belong to this event (or the asynchronous method) that corresponds to the asynchronous method? )). This allows Nodejs to ensure that each line of code written by the developer (each callback) is executed in the main thread.
1. In the process of an asynchronous program, if an error occurs, the asynchronous result is entered directly into the event queue, and the parameter passed in will be the first parameter of the callback function.

2. If the developer calls the blocking method in the callback function, the entire event polling is blocked, the events in the event queue are not processed in time, and node is stuck and then crashes. Because of this, some of the library methods in Nodejs are asynchronous and encourage users to invoke asynchronous methods. If an error is generated in the callback function, node crashes when the event is blocked from calling the corresponding asynchronous function .

In fact, when you see this, if you have a better understanding of Windows programming (especially for Windows interface programming), you may already think of the Windows message loop.

Yes, the event polling principle in Nodejs is similar to the principle of Windows message loops. The code written by the developer runs in the main thread, and if you write a blocking code, in the Windows desktop program, the interface will get stuck because the message is not processed in time.

Let's take a look at the following Nodejs code:

var fs = require (' FS ');
Fs.readfile (' Hello.txt ', function (err, data) {//Read files asynchronously
Console.log ("Read file End");
});
while (1) {
Console.log ("Call readFile over");
}

As above, although we use asynchronous methods to read the file, the "Read file end" will never output after the file has been read, meaning that the callback function of the ReadFile method will not execute. The reason is simple because the while loop of the subsequent main process does not exit, causing the next event poll not to start , so the callback function cannot execute (including all other callbacks). The fact is that all the code that developers write can only run on the same thread (let's call it the mainline).

About Async methods

The so-called asynchronous method is that calling the method does not block the calling thread, even if the method internally takes time-consuming action. you can understand that the method internally opens up a new thread to handle the task (the main process has been working, and the new thread that opened it handles the asynchronous work), while calling the Async method simply opens the new thread. The following code simulates the internal structure of an async method (just the simulation, not the actual):

In. NET, the callback function for each async method executes in another thread (not the calling thread), whereas in Nodejs, the callback function for each async method is still on the calling thread (which can be understood as the main thread). As for why, you can take a look at the section of the previous event polling, each callback function in Nodejs is called by an event poll in the main thread. This ensures that in Nodejs, any code written by the developer is run in the same thread (so-called single-threaded). Http://www.cnblogs.com/xiaozhi_5638/p/4268223.html

The message loop should be "pump", Message Queuing should be " data container ", Windows message should be " data ", and window process should be " processor ", then the whole structure should

Since the framework guarantees that the final application will continue to work properly, the conclusion in this chapter suggests that there must be a structure within the framework that is capable of repeating the problem, that is, the "pump", the "continuous" and "dynamic" nature of the pump, which fully satisfies the requirements of the framework. If you need to graphically visualize this abstract relationship, see 10-18:

Since our final application is extended on the basis of the framework, it shows that the main operational logic of the application, the main process control is determined by the framework, the framework controls the application's start-up , determines the main process shift , is responsible for invoking the "extension Code" written by the framework consumer, in short, the framework ensures that the final application continues to function properly.

These extension codes are often mentioned as hook functions (or some properties), and then the rest of the template is written dead. Only the hooks are fixed.

Node. JS Event Polling (1)

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.