1. The role of node.js,
The meaning of I/O, (I/O is the abbreviation of input/output, such as: the keyboard type text, input, and the text is displayed on the screen. Mouse moves, the mouse is moved, the mouse is moved on the screen, the terminal input, and the output seen. etc.)
The problem that node.js wants to solve, (process input, high concurrency. For example, there may be millions of gamers in online games, and millions of inputs, etc.) (Node.js is suitable for category: Node.js is most suitable when an application needs to send and receive data on the network. This may be a third-party API, networked device, or real-time communication between a browser and a server)
The meaning of concurrency, (the term concurrency describes that things will happen at the same time and may interact with each other. Node's evented I/O model allows us to avoid the common problems of interlocking and concurrency in multithreaded asynchronous I/O)
Demonstration 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 require node.js to access three URLs and report the response received and the time it took.
We can see that the output time is different for the two times. Affected by various factors, the time to resolve DNS requests, busy server programs, etc.
Why is javascript an event-driven language
JavaScript revolves around the event architecture that was originally associated with the Document Object Model (DOM). Developers can do things when events occur. These events include users clicking on an element, the page completes loading, etc. Using events, developers can write listeners for events that are triggered when events occur.
2. Callback
1. What is a callback
2. Analyze the callback
A callback refers to passing a function as an argument to another function and is usually called after the first function is completed.
Example: For example, the hide() method in jquery,
Js code
1,$("p").hide('slow'); 2,$("p").hide('slow',function(){alert("The paragraph is now hidden")});Callbacks are optional.
1 No callback is needed
2. There is a callback. When the paragraph is hidden, it will be called, showing an alert prompt.
In order to see the difference between code with and without callbacks
Js code
$("p").hide('slow'); alert("The paragraph is now hidden");//1 $("p").hide('slow',function(){alert("The paragraph is now hidden")});//21. There is no callback, and the execution order is the same. However, we can see that the p paragraph has not been completely hidden, alert comes out.
2. There is a callback, and the execution is done after the hide is completed.
Analyze 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. Time to go to work!'); });Output:
Having barakfast of foam, coffeeFinished breakfast. Time to go to work!
Here is a function created with three parameters, the third parameter is callback, which must be a function.
The haveBreakfast function records what you eat into the console and then calls the callback function passed to it as a parameter.
How to use callbacks for Node.js
Example of using filesystem module to read file content 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 in somefile.txt.
1. The fs (filesystem) module is requested for use in the script
2. The file path on the file system is provided as the first parameter to the fs.readFile method.
3. The second parameter is utf8, which indicates the encoding of the file
4. Provide the callback function as the 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 it, and the user saves the data returned by the read file.
7. Once the file is read, the callback will be called.
8. If err is true, an error will be thrown.
9. If err is false, then the data from the file can be used.
10. In this case, the data will be recorded on the console.
Another one is the http module, the http module allows 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); });Result: Got response:200
1. Request the http module for use in the script
2. Provide two parameters to the http.get() method
3. The first parameter is the option object. In this example, you need to get the home page of shapeshed.com
4. The second parameter is a callback function with the response as the parameter
5. When the remote server returns the corresponding function, the callback function will be triggered.
6. Record the response status code in the callback function. If there is any error, you can record it.
Next, let's see that 4 different I/O operations are happening, they all use callbacks
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 returns first?
The guess is that the two files read from disk are returned first, because there is no need to enter the network, but it is difficult for us to say which file will return first, because we don't know the file size. For the acquisition of two home pages, the script needs to enter the network, and the response time depends on many unpredictable things. The Node.js process will not exit until there is a registered callback that has not been triggered. Callbacks first solve unpredictability, and it is also an efficient way to deal with concurrency (or do more than one thing at a time).
Here are the results of my execution
Synchronous and asynchronous code
First look at the code, synchronize (or block) the code
Js code
function sleep(milliseconds){ var start = new Date().getTime(); while((new Date().getTime() -start) < millionseconds){ } } function fetchPage(){ console.log('fetching page'); sleep(2000); console.log('data returned from requesting page'); } function fetchApi(){ console.log('fetching api'); sleep(2000); console.log('data returned from the api'); } fetchPage(); fetchApi();When the script is running, the fetchPage() function will be called. Until it returns, the script's run is blocked. Before the fetchPage() function returns, the program cannot be moved to the fetchApi() function. This is called a blocking operation.
Node.js almost never uses this coding style, but calls callbacks 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 was 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 was an error" + e); }); } fetchPage(); fetchApi();When this code is allowed, you no longer wait for the fetchPage() function to return, and the fetchApi() function will be called immediately. The code is blocked by using callbacks. Once called, both functions listen to the return of the remote server and trigger the callback function.
Note that the return order of these functions cannot be guaranteed, but is related to the network.
Event loop
Node.js uses javascript's event loop 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 return data. Because the execution of the callback function is postponed until the event is reversed, there is no need to stop the execution, and the control flow can return to the Node runtime environment, allowing other things to happen.
Node.js is often regarded as a network programming framework because it is designed to handle uncertainty in data flows in the network. What contributes to such designs are event loops and use of callbacks, and they are like programmers who can write asynchronous code that responds to network or I/O events.
The rules to be followed are: the function must return quickly, the function must not be blocked, and long-running operations must be moved to another process.
What is not suitable for Node.js includes processing large amounts of data or running calculations for a long time. Node.js is designed to push data on the network and complete it instantly.