1.首先搭建nodej服务
var http=require('http');
var server = http.createServer(function (request, response) {
// TODO
});
server.listen(3200);
console.log("Server runing ...");
2.实现路由
var server = http.createServer(function (request, response) {
var pathName = url.parse(request.url).pathname;
response.write(pathName);
response.end();
});
3.读取静态文件
var server=http.createServer(function(request,response){
var pathName=url.parse(request.url).pathname;
var realPath='assets'+pathName
fs.exists(realPath,function(exists){
if(!exists){
response.writeHead(404,{
"Content-Type": "text/plain"
})
response.write('this request url'+pathName+'was not found');
response.end()
}else{
fs.readFile(realPath,"binary",function(err,file){
if(err){
response.writeHead(404,{
"Content-Type": "text/plain"
})
response.end()
}else{
response.writeHead(200,{
"Content-Type":contentType
})
response.write(file,"binary")
response.end()
}
})
}
})
});
在上面代码中assets目录下的静态文件都可以访问,构成静态服务器。
但是服务器中文件类型名都相同text/plain
3.MINE类型支持
针对不同文件显示不同content-type
exports.type={
'jpg':'image/jpeg'
}
如果想要包含所有文件,这里可以写全部的映射表
引入mime.js文件
var mine=require('./mime').type;
通过path.extname获取后缀名
var ext=path.extname(realPath)
ext=ext?ext.slice(1):'unkown'
var contentType=mine[ext]||'text/plain'
response.writeHead(200,{
"Content-Type":contentType
})
response.write(file,"binary")
response.end()
4.设置缓存
指定文件后缀和过期日期,建立config.js文件
exports.Expires = {
fileMatch: /^(gif|png|jpg|js|css)$/ig,
maxAge: 60 * 60 * 24 * 365
};
引入config.js文件
var Expires=require('./config').Expires;
在响应之前,如果匹配到了相应后缀文件,则添加过期时间头
if(ext.match(Expires.fileMatch)){
var expires=new Date();
expires.setTime(expires.getTime()+Expires.maxAge*1000)
response.setHeader('Expires',expires.toUTCString())
response.setHeader('Cache-Control','max-age='+Expires.maxAge)
}
现在响应头中多了两个header
浏览器发起请求判断是否过期,若没过期就不会发送请求,从缓存中读取。
fs.stat(realPath, function (err, stat) {
var lastModified = stat.mtime.toUTCString();
response.setHeader("Last-Modified", lastModified);
}
同时检测浏览器是否发送了if-modified-since,如果和lastModified 相同,则返回304
if (request.headers['if-modified-since'] && lastModified == request.headers['if-modified-since']) {
response.writeHead(304, "Not Modified");
response.end();
}