My Node.js Learning Path (iii)--node.js actions, callbacks, synchronous and asynchronous code, and event loops _node.js

Source: Internet
Author: User
Tags http request object model readfile

One, the role of Node.js,

I/o meaning, (I/O is the input/output of shorthand, such as: keyboard typing text, input, the screen to see the text display output.) Mouse movement, see the mouse movement on the screen. Terminal input, and see the output. Wait

Node.js want to solve the problem, (processing input, input, high concurrency.) If there are millions of players in an online game, there are million inputs, and so on) (Node.js fit: The node.js is most appropriate when the application needs to send and receive data on the network. This may be a Third-party API, networked device or real-time communication between the browser and the server.

The meaning of concurrency (the term concurrency describes things that happen at the same time and may interact with each other). Node's event-based I/O model gives us no need to worry about the interlocking and concurrency problems common in multithreaded asynchronous I/O

Demo Network I/O

JS Code

var http = require (' http '), 
  urls = [' www.baidu.com ', ' www.10jqka.com.cn ', ' www.duokan.com ']; 
function Fetchpage (URL) { 
  var start = new Date (); 
  Http.get ({host:url},function (res) { 
    console.log ("Got response from:" + URL); 
    Console.log ("Request took:", new Date ()-Start, "MS");} 
for (var i=0; i<urls.length; i++) { 
  fetchpage (urls[i]); 
 

Named, Node.js
We run node Node.js in the terminal.
Output:

We asked Node.js to access three URLs and report on the response and the time spent.
We can see that two times the output time is not the same. Affected by various effects, the time to resolve DNS requests, server busy programs, and so on.

Why JavaScript is an event-driven language
JavaScript surrounds the event schema originally associated with the Document Object Model (DOM). Developers can do things when the event occurs. These events have users clicking on an element, the page completes loading, and so on. With events, developers can write listeners of events that are triggered when an event occurs.

Two, callback (Callback)
1, what is a callback
2, profiling callback

A callback refers to passing a function as an argument to another function, and is usually invoked after the first function completes.

Example: the Hide () method in jquery,
JS Code

1,$ ("P"). Hide (' slow '); 
2,$ ("P"). Hide (' slow ', function () {alert ("the paragraph is now hidden")}); 

The callback is optional,
1 You don't need a callback.
2, there is a callback, and when the paragraph is hidden, it will be invoked to display an alert prompt.

In order to see the difference between the code with and without the callback
JS Code

$ ("P"). Hide (' slow '); 
Alert ("The paragraph is now hidden");//1 
 
$ ("P"). Hide (' slow ', function () {alert ("the paragraph was now hidden")});//2 

1, there is no callback, the order of execution is the same however, we can see that the p paragraph is not yet hidden completely, alert comes out
2, there is a callback, the execution is after the hide is completed in alert

Profiling callbacks
JS Code

function Havebreakfast (food,drink,callback) { 
  console.log (' having barakfast of ' + Food + ', ' + drink); 
  if (callback && typeof (callback) = = "function") { 
    callback () 
  } 
} 
 
Havebreakfast (' foast ', ' coffee ', function () { 
  Console.log (' finished breakfast. Work! '); 
 


Output:

Having barakfast of Foast,coffee
finished breakfast. work!

Here is the creation of a function that has three parameters, the third parameter is callback, and this argument must be a function.
The Havebreakfast function logs what is eaten to the console and then invokes the callback function passed as a parameter to it.

Node.js How to use callbacks

Example of using FileSystem module to read the contents of a file from disk in Node.js

JS Code

var fs = require (' FS '); 
 
Fs.readfile (' somefile.txt ', ' UTF8 ', function (err,data) { 
  if (err) throw err; 
  Console.log (data); 

The result is: the content inside the somefile.txt.
1,fs (filesystem) module is requested for use in script
2, the file path on the file system is provided to the Fs.readfile method as the first parameter
3, the second parameter is UTF8, which represents the encoding of the file
4, the callback function is supplied as a third parameter to the Fs.readfile method
5, the first parameter of the callback function is err, which is used to save the error returned when reading the file
6, the second parameter of the callback function is to hit him, and the user saves the data returned by reading the file.
7, once the file is read, the callback is invoked
8, If Err is true, then an error is thrown
9, if Err is false, then data from the file can be used
10, in this case, the data is logged to the console.

Again, HTTP modules, HTTP modules enable developers to create HTTP clients and servers.

JS Code

var http = require (' http '); 
 
Http.get ({host: ' shapeshed.com '},function (res) { 
  console.log ("Got response:" + Res.statuscode); 
}). On (' Error ', function (e) { 
  console.log ("Got error:" + e.message); 
 
}); 

Results: Got response:200
1, Request HTTP module, in order to use in script
2, give the Http.get () method with two parameters
3, the first parameter is an option object. In this example, you are asked to get Shapeshed.com's home page
4, the second parameter is a callback function with the response as a parameter
5, the callback function is triggered when the remote server returns the corresponding.
6, the response status code is recorded in the callback function, and can be recorded if there is an error.

Next, let's look at 4 different I/O operations that are happening and they all use the callback

JS Code

var fs = require (' FS '), 
  http = require (' http '); 
 
Http.get ({host: ' www.baidu.com '},function (res) { 
  console.log (' baidu.com '); 
}). On (' Error ', function (e) { 
  console.log ("Got error:" + e.message); 
 
}); 
 
Fs.readfile (' somefile.txt ', ' UTF8 ', function (err,data) { 
  if (err) throw err; 
  Console.log ("Somefile"); 
 
Http.get ({host: ' www.duokan.com '},function (res) { 
  console.log (' duokan.com '); 
}). On (' Error ', function (e) { 
  console.log ("Got error:" + e.message); 
 
}); 
 
Fs.readfile (' somefile2.txt ', ' UTF8 ', function (err,data) { 
  if (err) throw err; 
  Console.log ("Somefile2"); 
 

Can we know which operation to return first?
The guess is that two files read from disk are returned first because there is no need to enter the network, but it is difficult to say which file to return first, because we do not know the size of the file. For two home pages, the script goes into the network, and the response time relies on many unpredictable things, and the node.js process does not exit until there are registered callbacks that have not been triggered. The callback first solves the unpredictable approach, and he is an efficient way to deal with concurrency (or more than one thing at a time).
Here are the results I've done.



Synchronous and asynchronous code

Look at the code first, synchronize (or block) the code

JS Code

function sleep (milliseconds) { 
  var start = new Date (). GetTime (); 
  while (new Date (). GetTime ()-start) < milliseconds) { 
 
  } 
} 
function Fetchpage () { 
  Console.log (' Fetching page '); 
  Sleep (); 
  Console.log (' data returned from requesting page '); 
} 
function Fetchapi () { 
  console.log (' fetching API '); 
  Sleep (); 
  Console.log (' data returned from the API '); 
} 
Fetchpage (); 
Fetchapi (); 


When the script is run, the Fetchpage () function is invoked until it returns, the script runs blocked, and the program cannot be moved to the FETCHAPI () function until the Fetchpage () function returns. This is called a blocking operation.
Node.js almost never used this encoding style, but invoked the callback asynchronously.
Look at the code below,

JS Code

var http = require (' http '); 
 
function Fetchpage () { 
  console.log (' fetching page '); 
  Http.get ({host: ' www.baidu.com ', Path: '/?delay=2000 '}, 
    function (res) { 
      console.log (' data returned from Requesting page '); 
    On (' Error ', function (e) { 
      Console.log ("There is an error" + E);} 
    ) 
function Fetchapi () { 
  console.log (' fetching API '); 
  Http.get ({host: ' www.baidu.com ', Path: '/?delay=2000 '}, 
    function (res) { 
      console.log (' data returned from Requesting API '); 
    On (' Error ', function (e) { 
      Console.log ("There is an error" + E);} 
    ) 
Fetchpage (); 
Fetchapi (); 

When this code is allowed, it is no longer waiting for the fetchpage () function to return, and the Fetchapi () function is immediately invoked. The code is non-blocking by using a callback. Once invoked, two functions listen for the return of the remote server and trigger the callback function.
Note that the return order of these functions is not guaranteed, but is related to the network.

Event Loops

Node.js uses JavaScript's event loops to support the asynchronous programming style it advocates. Basically, the event loop allows the system to save the callback function first and then run when the event occurs in the future. This can be a database return data or an HTTP request to return data. Because the execution of the callback function is deferred until the event is reversed, the control flow can return to the node runtime environment to allow other things to happen without stopping execution.

Node.js is often treated as a network programming framework because it is designed to handle the uncertainties of data flow in the network. This design is facilitated by event loops and the use of callbacks, which programmers can write asynchronous code that responds to a network or I/O event.

The rules to follow are: functions must be returned quickly, functions should not be blocked, and long-running operations must be moved to another process.
Where the node.js is unsuitable, it involves processing large amounts of data or running computations for a long time. Node.js is designed to push data in the network and to complete it instantaneously.

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.