node.js 中有同步讀取文件和異步讀取文件的區(qū)別
同步讀取就是順序進(jìn)行贬堵,文件讀取操作不進(jìn)行完就不進(jìn)行下一步操作
異步讀取就是文件讀取操作時,另起了一個線程玄糟,繼續(xù)進(jìn)行
異步的方法函數(shù)最后一個參數(shù)為回調(diào)函數(shù)巴比,回調(diào)函數(shù)的第一個參數(shù)包含了錯誤信息(error)闷哆。
文件讀取
05_readfile.js
var http = require('http');
var optfile = require('./models/optfile');
http.createServer(function(request, response) {
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
if (request.url !== "/favicon.ico") { //清除第2此訪問
console.log('訪問');
response.write('hello,world');
var path = "D:\\learn\\nodejs\\05\\models\\test.txt"
// optfile.readfile(path);
optfile.readfileSync(path);
response.end('hell,世界'); //不寫則沒有http協(xié)議尾
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
./models/optfile.js
var fs= require('fs');
module.exports={
readfile:function(path){ //異步執(zhí)行
fs.readFile(path, function (err, data) {
if (err) {
console.log(err);
}else{
console.log(data.toString());
}
});
console.log("異步方法執(zhí)行完畢");
},
readfileSync:function(path){ //同步讀取
var data = fs.readFileSync(path,'utf-8');
console.log(data);
console.log("同步方法執(zhí)行完畢");
return data;
}
}
輸出:
同步:
readfile.png
異步:
readfile_sync.png
使用閉包異步讀取文件后寫到前端
05_readfile.js
var http = require('http');
var optfile = require('./models/optfile');
http.createServer(function(request, response) {
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
if (request.url !== "/favicon.ico") { //清除第2此訪問
// 閉包
function recall(data) {
response.write(data)
response.end('hell,世界')
}
console.log('訪問');
response.write('hello,world');
var path = "D:\\learn\\nodejs\\05\\models\\test.txt"
optfile.readfile(path, recall);
// optfile.readfileSync(path);
// response.end('hell,世界'); //不寫則沒有http協(xié)議尾
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
./models/optfile.js
var fs= require('fs');
module.exports={
readfile:function(path, recall){ //異步執(zhí)行
fs.readFile(path, function (err, data) {
if (err) {
console.log(err);
}else{
console.log(data.toString());
recall(data)
}
});
console.log("異步方法執(zhí)行完畢");
},
readfileSync:function(path){ //同步讀取
var data = fs.readFileSync(path,'utf-8');
console.log(data);
console.log("同步方法執(zhí)行完畢");
return data;
}
}