封装静态WEB服务器
我的上一篇博文http://blog.csdn.net/cckevincyh/article/details/78637576中讲到了如何创建一个服务器去加载静态文件,现在我们根据之前的代码,我们重新对我们的静态web服务器进行封装。
原本我们的主程序中的代码如下:
//引入http模块
var http=require('http');
//fs模块
var fs = require('fs');
//path模块
var path = require('path'); /*nodejs自带的模块*/
//url模块
var url = require('url');
//引入扩展名的方法是在文件里面获取到的。
var mimeModel = require('./model/getmimefromfile.js');
//console.log(mimeModel.getMime('.css')); //获取文件类型
http.createServer(function(req,res){
//http://localhost:8001/news.html /news.html
//http://localhost:8001/index.html /index.html
//css/dmb.bottom.css
//xxx.json?214214124
var pathname = url.parse(req.url).pathname;
console.log(pathname);
if(pathname == '/'){
pathname = '/index.html'; /*默认加载的首页*/
}
//获取文件的后缀名
var extname = path.extname(pathname);
if(pathname != '/favicon.ico'){ /*过滤请求favicon.ico*/
//console.log(pathname);
//文件操作获取 static下面的index.html
fs.readFile('static/' + pathname,function(err,data){
if(err){ /*没有这个文件*/
console.log('404');
fs.readFile('static/404.html',function(error,data404){
if(error){
console.log(error);
}
res.writeHead(404,{"Content-Type":"text/html;charset='utf-8'"});
res.write(data404);
res.end(); /*结束响应*/
})
}else{ /*返回这个文件*/
var mime = mimeModel.getMime(fs,extname,function(mime){
res.writeHead(200,{"Content-Type":"" + mime + ";charset='utf-8'"});
res.write(data);
res.end(); /*结束响应*/
});
}
})
}
}).listen(8001);
为了避免主程序的代码太多太乱,不利于维护,我们需要把我们的一些代码封装到router.js中。
//fs模块
var fs=require('fs');
//path模块
var path=require('path'); /*nodejs自带的模块*/
//url模块
var url=require('url');
//获取文件类型的方法 私有
function getMime(extname,callback){ /*获取后缀名的方法*/
fs.readFile('./mime.json',function(err,data){
if(err){
console.log('mime.json文件不存在');
return false;
}
//console.log(data.toString());
var Mimes=JSON.parse(data.toString());
var result= Mimes[extname] || 'text/html';
callback(result)
})
}
exports.statics=function(req,res,staticpath){
var pathname=url.parse(req.url).pathname; /*获取url的值*/
if(pathname=='/'){
pathname='/index.html'; /*默认加载的首页*/
}
//获取文件的后缀名
var extname=path.extname(pathname);
if(pathname!='/favicon.ico'){ /*过滤请求favicon.ico*/
//console.log(pathname);
//文件操作获取 static下面的index.html
fs.readFile(staticpath+'/'+pathname,function(err,data){
if(err){ /*么有这个文件*/
console.log('404');
fs.readFile(staticpath+'/404.html',function(error,data404){
if(error){
console.log(error);
}
res.writeHead(404,{"Content-Type":"text/html;charset='utf-8'"});
res.write(data404);
res.end(); /*结束响应*/
})
}else{ /*返回这个文件*/
getMime(extname,function(mime){
res.writeHead(200,{"Content-Type":""+mime+";charset='utf-8'"});
res.write(data);
res.end(); /*结束响应*/
});
}
})
}
}
封装好之后,主程序中就只需要引入router文件,并调用statics方法:
//引入http模块
var http=require('http');
//引入扩展名的方法是在文件里面获取到的。
var router=require('./model/router.js');
//console.log(mimeModel.getMime('.css')); //获取文件类型
http.createServer(function(req,res){
router.statics(req,res,'static');
}).listen(8001);
浏览器中输入http://localhost:8001/index.html就可以看到如下结果了: