Use events. Eventemitter controlling the node. JS Program Execution Process

Source: Internet
Author: User
Tags emit readfile

Use events. Eventemitter controlling the node. JS Program Execution Process

The title may not be too right to write, we understand the spirit;

node. JS is a platform built on the Chrome JavaScript runtime.

node. JS is an event-driven I/O server-side JavaScript environment, based on the Google V8 engine, the V8 engine executes JavaScript very quickly and with great performance.

The immediate manifestation of node. JS asynchronous programming is callbacks.

Asynchronous programming relies on callbacks to implement, but it cannot be said that the program is asynchronous after using the callback.

The callback function is called after the task is completed, and node uses a large number of callback functions, and all node APIs support the callback function.

For example, we can read the file while executing other commands, and after the file is read, we return the contents of the file as parameters to the callback function.

This will not block or wait for file I/O operations when executing code. This greatly improves the performance of node. JS and can handle a large number of concurrent requests.

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.

The main idea is that the node. JS program does not "wait" unlike most code that executes from top to bottom.

When the program executes to a callback function that requires I/O execution time, it proactively skips the wait and executes the following code;

Thus there is a disadvantage: the input (parameter) of a particular function is the return of several callback functions;

The execution mechanism of the program will skip the wait for the callback function, execute the following specific function directly, and the specific function does not wait for the input returned by the callback function;

Examples are as follows:

varFS = require ("FS");
varArray = [1, 2, 3, 4, 5];varJSON = {};
for(Let index = 0; index < array.length; index++) {Const element=Array[index]; Deal (element,function(ret) {json[element]=ret; Console.log (JSON); });} Console.log (JSON); functiondeal (NUM, callback) {Fs.readfile (num+ '. txt ',function(err, data) {if(Err) {console.error (err); Callback (ERR); } Else{callback (data.tostring (). Trim ()); } });} Object {} Object {1: "11111"}object {1: "11111", 5: "55555"}object {1: "11111", 3: "33333", 5: "55555"}object {1: "11111", 3: "33333", 4: "44444", 5: "55555"}object {1: "11111", 2: "22222", 3: "33333", 4: "44444", 5: "55555"}

The callback function takes the contents of the array as the file name, reads the data in the file as the return value;

However, the program does not wait for the file to be read, the print operation is performed without a single file read, and the empty object is output;

If you want to perform file reads in sequential order, printing output after reading is not only a waste of time, but a layer of code redundancy,

The array size (number of callback functions) cannot be estimated.

All asynchronous I/O operations of node. JS send an event to the event queue when it is finished.

The solution is: node. JS's event-driven feature, which allows printing as an event, after all the callback functions are executed, and then the print operation is triggered;

varFS = require ("FS");var events = require (' events '); var emitter = new events. Eventemitter (); varArray = [1, 2, 3, 4, 5];varCount = 0;varJSON = {}; for(Let index = 0; index < array.length; index++) {Const element=Array[index]; Deal (element,function(ret) {json[element]=ret;    Console.log (JSON); });} Emitter.on ( ' Databack ', function () { count++; if(Count = =array.length)    { console.log (JSON); }}); functiondeal (NUM, callback) {Fs.readfile (num+ '. txt ',function(err, data) {if(Err) {console.error (err);            Callback (ERR); Emitter.emit ( ' Databack '); } Else{callback (data.tostring (). Trim ()); Emitter.emit ( ' Databack '); }    });} Object {1: "11111"}object {1: "11111", 4: "44444"}object {1: "11111", 3: "33333", 4: "44444"}object {1: "11111", 3: "33333", 4: "44444", 5: "55555"}object {1: "11111", 2: "22222", 3: "33333", 4: "44444", 5: "55555"}Object { 1: "11111", 2: "22222", 3: "33333", 4: "44444", 5: "55555"}

Add print events and event triggers to the program, and all the data is set and then printed,

Although there is a problem with the lock locking of count, the actual problem has been solved;

Uh, uh.

Referenced and rewritten programs come from the node. JS Tutorial | Beginner's Tutorial

node. js File System | Beginner's Tutorial

node. js Eventemitter | Beginner's Tutorial

J.x.duasonir

Use events. Eventemitter controlling the node. JS Program Execution Process

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.