node. JS Road "third" Nodejs asynchronous implementation

Source: Internet
Author: User
Tags emit

Nodejs Asynchronous implementation

The immediate manifestation of node. JS Asynchronous programming is the callback, which is implemented by callbacks, but cannot be said to use callbacks.

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 execute other commands while reading the file, and when the file is read, we return the contents of the file as parameters of the callback, so that there is no blocking or waiting for I/O operation when executing the code

This is a hit. Improved node. JS performance and can handle a large number of concurrent requests.

One, block code example

1. Create a test file the contents of the Text.txt file are as follows:

File I/O operation: Open the file ==> handsome guy.

Create a Index.js file

#!/usr/bin/env nodevar fs = require ("FS"); var data = Fs.readfilesync (' test.txt '); Console.log (data.tostring ()); Console.log (' handsome man performs command test ~ ~ ~ ');

2. Implementation results

Luotimdemacbook-pro-2: Bin luotim$ node Index.js file i/O operation: Open the file ==> handsome very handsome brother execute command test ~ ~ ~

Output commands that are performed before I/O operations can be seen from the results

II. implementation of non-blocking code

Modify Code

# !/usr/bin/env Node  = require ("fs"); Fs.readfile ('test.txt' ) , Function (error,data) {    ifreturn  console.error (error);    Console.log (Data.tostring ());}); Console.log (" Asynchronous program Test ~ ~");

2. Implementation results

Luotimdemacbook-pro-2: Bin luotim$ node index.js Async program Test ~ ~ file I/O operation: Open the file ==> handsome guy.

From the results can be seen in the first program after the completion of the program, the second instance we do not need to wait for the file to be read so that you can read the file while executing the subsequent code, greatly improving the program performance.

For Nodejs, the blocking is executed sequentially, not blocking does not need to be executed in sequence directly to the callback function to execute the related I/O operations.

node. js Event Loop

Nodejs is a single-process and single-threaded application, but supports concurrency through events and callbacks ( see async implementations above ), so performance is very high.

And each API of Nodejs is asynchronous and runs as a separate thread, using asynchronous function calls, and handling concurrency!

Nodejs basically all of the event mechanisms are implemented using the "Observer pattern" in design mode

# The Observer Pattern Observer pattern (sometimes called the Publish (publish)-subscribe (Subscribe) mode, model-view mode, source- Listener (Listener) mode, or slave mode) is one of the software design patterns. In this mode, a target object manages all the observer objects that are dependent on it and proactively notifies when its own state changes. This is usually done by calling the methods provided by each observer. This pattern is often used to implement an event-handling system. 

The node. JS single thread resembles an event loop that enters a while (true), knowing that no event observer exits, and that each asynchronous event generates an event watcher that invokes the callback function if no 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 the structure is returned to the user at the beginning of the queue.

Because webserver always accepts requests without waiting for any I/O Read and write operations (non-blocking I/O or event-driven I/O)

The whole drive process is as simple as this.

Ii. binding and triggering events through the events module

1. Import the module and instantiate the object

// Introducing the Events module var events = require ("events"); // Create a Evenemitter object var new events. Eventemitter ();

2, binding event handlers, when the event triggered after the execution of the program

// handler for binding events and Events Evenemitter.on (' Evenname ', eventHandler);

3, can be triggered by the program

// we can trigger event evenemitter.emit (' Evenname ') through the program;

Instance:

#!/usr/bin/env node//Introducing the Events modulevarEvents = require ("Events");//Create a Evenemitter objectvarEventemitter =Newevents. Eventemitter ();//To create an event handlervarConnecthandler =functionconnected () {Console.log (' Connection succeeded. ‘); //Triggering data_received EventsEventemitter.emit (' data_received ');};//binding Connection Event handlersEventemitter.on (' Connection ', Connecthandler); //binding data_received events with anonymous functionsEventemitter.on (' data_received ',function() {Console.log (' Data received successfully. ‘);});//Triggering connection EventsEventemitter.emit (' Connection '); Console.log ("The program has finished executing. ");


Grooming Flowchart: (for grooming) The binding execution of events

node. JS Road "third" Nodejs asynchronous implementation

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.