理解IO

注意这里的异步式执行结果是,控制台会先打印read over,然后才打印package.json文件中的内容,也就是说,线程执行文件IO时,继续先执行了console.log(‘read over‘); 待读取操作结束后通知线程响应此时的回调函数,执行了结果打印操作。
 1 /*
 2 * 异步式(Asynchronous) I/O Example. 7 */
 8 var file = require(‘fs‘);//声明对象
 9 //异步式读取
10 file.readFile(‘file.json‘,‘utf-8‘, function(error,data) {
11     if (error) {
12         console.error(error);
13     } else {
14         console.log(data);
15     }
16 });
17 //读取结束
18 console.log("read over.");
运行结果:
1 >node readfile.js
2 >read over.
3 >{
4         "description" : "this is Synchronous I/O and Aynchronous I/O test."
5  }  
同步式:
此次执行的结果则是先读取完package.json文件的内容并打印, 然后打印read over.
 1 /**
 2 * 同步式(Synchronous) I/O Example.
 3 */
 6 var file = require(‘fs‘);//声明对象
 7 //readFileSync()方法为NodeJs官方提供的同步式文件读取方法,
 8 //但是官方并不推荐。
 9 var data = file.readFileSync(‘file.json‘, ‘utf-8‘);
10 console.log(data);
11 //读取结束
12 console.log("read over.");
1 >node readfile.js
2 >{
3         "description" : "this is Synchronous I/O and Aynchronous I/O test."
4    }  
5 >read over.  
NodeJS示例异步式(Asynchronous)IO编程和与同步式Synchronous)IO,布布扣,bubuko.com
NodeJS示例异步式(Asynchronous)IO编程和与同步式Synchronous)IO
原文:http://www.cnblogs.com/zivxiaowei/p/3632482.html