App.js:
var http=require("http");
var router=require("./router");
http.createServer(function(req,res){
router(req,res,"./static");
}).listen(8100);
router.js:
var fs=require("fs");
var url=require("url");
//path模塊 解析路徑後綴
var path=require("path");
var mime=require("./readmime");
module.exports=function(req,res,static){
var pathname=url.parse(req.url).pathname;
if(pathname!="/favicon.ico"){
if(pathname=="/"){
pathname="/index.html";
}
//網頁取出來是index.html,少一個/ 因此要在pathname="index.html"的index.html前加/ 加上之後網頁取出來的是/index.html
//console.log(pathname);
fs.readFile(static+pathname,function(err,data){
if(err){
console.log(404);
return false;
}
//exname取當前文件的後綴名 .jpg
var exname=path.extname(pathname);
mime(exname,function(result){
res.writeHead(200,{"Content-Type":result+";charset=utf-8"});
res.write(data);
res.end();
});
});
}
}
readmime.js:
var fs=require("fs");
module.exports=function(dir,callback){
//dir是後綴名 .jpg callback括號裏的值指image/jpeg
fs.readFile("./mime.json",function(err,data){
if(err) throw err;
callback(JSON.parse(data.toString())[dir]);
});
}
目錄:
實現效果: