1 /**
2 * Created by Administrator on 2016/8/3.
3 */
4 var http = require("http");
5 //Node 导入文件系统模块
6 var fs = require("fs");
7 function start(req, res){
8 res.writeHead(200, {"Content-Type": "text/plain"});
9 res.write("异步读取文件和同步读取文件的对比!");
10 res.end("over");
11 }
12 //创建一个http服务器,并监听端口号为3001,host为127.1.1.1
13 var server = http.createServer(start).listen("3001","127.1.1.1",function(){
14 var port = server.address().port;
15 var host = server.address().address;
16 console.log("应用实例,访问地址为 http://%s:%s", host, port);
17 });
18 //异步读取[非阻塞]
19 console.log("异步开始:");
20 //异步读取文件内容的函数: readFile()
21 fs.readFile("index.txt", "utf-8", function(err, data){
22 if(err){
23 console.log(err);
24 }else{
25 console.log(data);
26 }
27 });
28 console.log("end异步");
29 //同步读取[阻塞,阻塞之后代码的执行]
30 console.log("同步开始:");
31 //同步读取文件内容的函数: readFileSync()
32 var data = fs.readFileSync("index.txt", "utf-8");
33 console.log(data);
34 console.log("end同步");