同步读文件
代码:https://github.com/fengchunjian/nodejs_examples/tree/master/readfile
//vim views/login.html
登录界面
//vim models/optfile.js
var fs = require('fs')
module.exports = {
readfileSync : function(path, res) {
var data = fs.readFileSync(path, "utf-8");
console.log(data);
console.log("同步方法执行完毕");
res.write(data);
}
}
\\vim readfile.js
var http = require('http');
var optfile = require("./models/optfile");
http.createServer(function (request, response) {
optfile.readfileSync("./views/login.html", response);
console.log("主程序执行完毕");
response.end();
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
node readfile.js
Server running at http://127.0.0.1:8000/
登录界面
同步方法执行完毕
主程序执行完毕
curl http://127.0.0.1:8000/
登录界面
异步读文件+路由升级
代码:https://github.com/fengchunjian/nodejs_examples/tree/master/routerv2
//vim views/login.html
登录界面
//vim views/zhuce.html
注册界面
\\vim models/optfile.js
var fs = require('fs')
module.exports = {
readfile : function(path, recall) {
fs.readFile(path, function(err, data) {
if (err) {
console.log(err);
} else {
recall(data);
}
});
console.log("异步方法执行完毕");
},
readfileSync : function(path, res) {
var data = fs.readFileSync(path, "utf-8");
console.log(data);
console.log("同步方法执行完毕");
res.write(data);
}
}
\\vim models/router.js
var optfile = require("./optfile");
module.exports = {
login : function(req, res) {
function recall(data) {
res.write(data);
res.end();
}
optfile.readfile("./views/login.html", recall);
},
zhuce : function(req, res) {
function recall(data) {
res.write(data);
res.end();
}
optfile.readfile("./views/zhuce.html", recall);
}
}
\\vim routercall.js
var http = require('http');
var url = require('url');
var router = require('./models/router');
http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
pathname = pathname.replace(/\//, '');
router[pathname](request, response);
console.log("主程序执行完毕");
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
node routercall.js
Server running at http://127.0.0.1:8000/
异步方法执行完毕
主程序执行完毕
异步方法执行完毕
主程序执行完毕
curl http://127.0.0.1:8000/login
登录界面
curl http://127.0.0.1:8000/zhuce
注册界面
参考文档
node.js教程5_读文件
http://edu.51cto.com/center/course/lesson/index?id=124529
nodejs5_读取文件(n5_readfile)
http://www.yuankuwang.com/web/index.php?r=respool/resview&rpid=37