__dirname 获取绝对路径
利用fs库,最好用这个函数
分模块路由
主文件:
var http = require("http");
var router = require("./router.js");
//创建服务器
http.createServer(function (req, res) {
if(req.url == "/"){
router.showIndex(req, res);
} else if(req.url.substr(0,9) == "/student/") {
router.showStudent(req, res);
} else {
router.show404(req, res);
}
}).listen(81, "127.0.0.1");
方法文件:
exports.showIndex = showIndex;
exports.showStudent = showStudent;
exports.show404 = show404;
function showIndex(req, res) {
res.writeHead(200, {"Content-Type":"text/html;charset=UTF-8"});
res.end("我是主页");
}
function showStudent(req, res) {
var id = req.url.substr(9,6);
res.writeHead(200, {"Content-Type":"text/html;charset=UTF-8"});
res.end("我是学生" + id);
}
function show404(req, res) {
res.writeHead(200, {"Content-Type":"text/html;charset=UTF-8"});
res.end("我是404");
}