nodejs搭建静态服务并设置缓存

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();
        }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值