1. Blocking. Synchronous.
1) Read the file: Input.txt
Beginner's Tutorial official website address: www.runoob.com
2) Main.js
1 var fs = require ("FS"); 2 3 // synchronous read, blocking code, sequentially executed 4 var data = Fs.readfilesync (' input.txt '); 5 6 console.log (data); 7 Console.log (data.tostring ()); 8 console.log ("program execution ends!");
Perform:
Attention:
First: The green box is output data. Can not be seen directly output read files, to use Data.tostring ()
Second: Blocking execution, is synchronous, in order.
If you specify a character set.
1 var fs = require ("FS"); 2 3 // synchronous read, blocking code, sequentially executed 4 var ' UTF8 ' ); 5 console.log (data); 6 Console.log (data.tostring ()); 7 console.log ("program execution ends!");
Perform:
2. Non-blocking, asynchronous:
1) the file to read. Input.txt
Beginner's Tutorial official website address: www.runoob.com
2) Main.js
1 varFS = require ("FS");2 3 //synchronous read, blocking code, sequentially executed4 //var data = Fs.readfilesync (' input.txt ');5 //console.log (data);6 //Console.log (data.tostring ());7 //console.log ("program execution ends!");8 9 //asynchronous reads, blocking, not in order.TenFs.readfile ("Input.txt",function(err, data) { One //ERR: AConsole.log ("ERR:", err); - if(err) { - return Console.error (err); the }; - console.log (data); - - Console.log (data.tostring ()); + }); - +Console.log ("program execution ends!");
Perform:
-----------------
If you specify a character set.
varFS = require ("FS");//synchronous read, blocking code, sequentially executed//var data = Fs.readfilesync (' input.txt ');//console.log (data);//Console.log (data.tostring ());//console.log ("program execution ends!");//asynchronous reads, blocking, not in order.//fs.readfile ("Input.txt", function (err, data) {////err://Console.log ("ERR:", err);//if (err) {//Console.error (err);// };//console.log (data);//Console.log (data.tostring ());// });//console.log ("program execution ends!");Fs.readfile ("Input.txt","UTF8",function(err, data) {//ERR:Console.log ("ERR:", err); if(Err) {return console.error (err); }; Console.log (data); Console.log (Data.tostring ());}); Console.log ("Program execution is over!");
Reference Links:
node. JS callback function
node. JS callback function 1) block, synchronous 2) non-blocking, asynchronous.