node. js asynchronous I/O with event-driven

Source: Internet
Author: User
Tags emit event listener readfile

The biggest feature of node. JS is the programming pattern of asynchronous I/O (or non-blocking I/O) that is tightly coupled to events. This
Mode is very different from the traditional synchronous I/O linear programming idea because the control flow is largely dependent on the event
and callback functions to organize, a logic to split into several units.

Blocking and threading
What is blocking (block)? Lineif disk read-write or network communication (collectively referred to as I/O operations) is encountered during execution),
It usually takes a long time for the operating system to deprive the thread of CPU control to suspend execution,
When the resource is ceded to other worker threads, this thread scheduling is called blocking. When the I/O operation is complete, the operating system
The blocking state of this thread is lifted and its control over the CPU is restored to continue execution. This I/O mode is the
Synchronous I/O (synchronous I/O) or blocking I/O (Blocking I/O).
Accordingly, asynchronous I/O (asynchronous I/O) or non-blocking I/O (non-blocking I/O) is
All I/O operations do not adopt a blocking policy. When a thread encounters an I/O operation, it does not wait for I/O operations in a blocking manner
Completion or return of the data, but simply sends the I/O request to the operating system and proceeds to the next statement. When the action
When the system completes an I/O operation, the thread that notifies the I/O operation is notified as an event, and the thread handles the
Event. In order to handle asynchronous I/O, threads must have an event loop that continually checks for unhandled events, sequentially to
To deal with.
In blocking mode, a thread can only handle one task, and to increase throughput must be through multithreading. Rather than blocking
mode, a thread is always performing a compute operation, and the CPU core utilization used by this thread is always 100%,
I/O is notified as an event. In blocking mode, multithreading tends to increase system throughput because a thread is blocking
When there are other threads at work, multithreading can make the CPU resources not wasted by the threads in the blocking. In non-blocking mode, the
, the thread is not blocked by I/O and is always using the CPU. The benefits of multithreading are only in the case of multicore CPUs
Using more cores, and the single thread of node. JS can bring the same benefits. That's why node. JS uses a single
thread, non-blocking event programming mode。

asynchronous I/O is less of a multithreaded overhead. For the operating system, the cost of creating a thread is very expensive,
It needs to be allocated memory, scheduled, while the thread switch to perform memory paging, the CPU cache is
Empty, when switching back to the time to re-read information from memory, destroying the local data. ①
Of course, the disadvantage of asynchronous programming is that it does not conform to people's general programming thinking, it is easy to make control flow obscure
Difficult to understand, to encode and debug all bring no small difficulties. Developers who are accustomed to traditional programming patterns have just come into contact with large-scale
Step application often will be at a loss, but slowly habits will be much better later. However, asynchronous programming is still more difficult,
But the good news is that there are many libraries, such as async, that specialize in solving asynchronous programming problems, see Section 6.2.2.

Let's look at how to read a file asynchronously in node. js, here's an example:
Readfile.js
var fs = require (' FS ');
Fs.readfile (' file.txt ', ' utf-8 ', function (err, data) {
if (err) {
Console.error (ERR);
} else {
Console.log (data);
}
});
Console.log (' end. ');
The results of the operation are as follows:
End.
Contents of the file.

node. JS also provides an API for synchronizing read files:
Readfilesync.js
var fs = require (' FS ');
var data = Fs.readfilesync (' file.txt ', ' utf-8 ');
Console.log (data);
Console.log (' end. ');
The result of the run is different from the previous, as follows:
$ node Readfilesync.js
Contents of the file.
End.

The only work that Fs.readfile calls is to send an asynchronous I/O request to the operating system and immediately
returns and executes the following statement, entering the event loop to listen for events after execution. when FS receives an I/O request to complete
event, the event loop actively invokes the callback function to complete the subsequent work. So we'll see end first, and then we'll see
Contents of the File.txt file

Event
All asynchronous I/O operations in node. JS send an event to the event queue when they are finished . In the eyes of developers, things
Provided by the Eventemitter object. The former mentioned Fs.readfile and Http.createserver's back
The function is implemented by Eventemitter. Let's use a simple example to illustrate Eventemitter
Use of:

var eventemitter=require ("Events"). Eventemitter;
var event=new eventemitter ();

Event.on ("Some_event", function () {
Console.log ("Some event occured");
});
SetTimeout (function () {
Event.emit ("Some_event");
},1000);

Run this code, 1 seconds after the console output some_event occured. The principle is that the event object
Registered a listener for event some_event, and then we passed the setTimeout after 1000 milliseconds to
The event object sends events some_event, and the listener for Some_event is called.
We will discuss the use of the Eventemitter object in detail in section 4.3.1.
node. js's event loop mechanism
When does node. js get into the event loop? The answer is that the node. JS program starts with the event loop,
loop ends, all logic is the callback function of the event , so node. js is always in the event loop, and the program entry is
The callback function for the first event in an event loop. The callback function for the event may issue an I/O request or
Direct emission (emit) event, after execution, returns the event loop, which checks the event queue for
Handle the event until the end of the program. Figure 3-5 illustrates the principle of the event loop.

Unlike other languages, node. JS does not have an explicit event loop, similar to Ruby's Eventmachine::run ()
function does not exist in node. js. node. js's event loop is not visible to developers and is implemented by the Libev library. Libev
Supports multiple types of events, such as Ev_io, Ev_timer, ev_signal, Ev_idle, etc., in node. js
Eventemitter package. Each iteration of the Libev event loop is a Tick in Node.js,Libev not
Check to see if there is an active, detectable event listener that exits the event loop until it is detected, and the process ends.

Node. js asynchronous I/O and event-driven

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.