Node basis: 2

Node.js callback function

Node.js is asynchronous programming directly reflects the callback.

Relying on callback asynchronous programming to achieve, but can not say that after using the callback of the asynchronous program.

The callback function will be called after the completion of the task, Node uses a lot of callbacks, Node API supports all callback functions.

For example, while we can read the file, execute other commands while, after reading the file is complete, we will file contents as an argument callback function returns. So that when no execution code or blocked waiting for the file I / O operations. This greatly improves the performance of Node.js can handle a large number of concurrent requests.

The callback function generally as the last parameter to the function appears:

function foo1(name, age, callback) { } function foo2(value, callback1, callback2) { }

Blocking code examples

Create a file input.txt, reads as follows "

Rookie tutorial official website address: the WWW . Runoob . COM

Create main.js file, the code is as follows:

var fs = require("fs");

var data = fs.readFileSync('input.txt');

console.log(data.toString());
console.log ( " the program to complete! " );

 

Code executes the above results are as follows:

$ node main.js
Rookie tutorial official website address: www.runoob.com

Program to complete !

Examples of non-blocking codes

 

Creating main.js file, the code is as follows:

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);
    console.log(data.toString());
});

console.log ( " the program to complete! " );

Code executes the above results are as follows:

 
The Node main $ . JS
 program to complete! Newbie tutorial official website address: the WWW . Runoob . COM

Guess you like

Origin www.cnblogs.com/xiaohuizhenyoucai/p/11021306.html