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
    评论
使用Node.js搭建本地服务器非常简单。首先,我们需要安装Node.js。 安装完成后,打开终端(或命令行窗口),进入想要搭建服务器的文件夹。 创建一个新的Node.js文件,命名为server.js(或其他任何你喜欢的名称),然后将以下代码复制到该文件中: ```javascript const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { let filePath = path.join(__dirname, req.url); let contentType = 'text/html'; fs.exists(filePath, (exists) => { if (exists) { fs.readFile(filePath, (error, content) => { if (error) { res.writeHead(500); res.end('Server Error'); } else { res.writeHead(200, { 'Content-Type': contentType }); res.end(content, 'utf-8'); } }); } else { res.writeHead(404); res.end('File Not Found'); } }); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); }); ``` 上述代码使用了Node.js的HTTP、FS和Path模块。server.js文件创建了一个HTTP服务器。当有请求发送到服务器时,它会检查请求的URL地址是否是文件路径,并将请求的文件作为响应发回给客户端。 在终端中运行以下命令启动服务器: ``` node server.js ``` 这将在本地启动一个HTTP服务器,监听在3000端口上。你可以通过浏览器访问http://localhost:3000/ 来访问该服务器。 请注意,在代码中,`contentType`变量默认设置为'text/html',这意味着服务器会将所有请求的文件作为HTML文件返回。你也可以根据需要更改它,例如如果你想返回CSS文件,可以将其设置为'text/css'。 以上就是使用Node.js搭建本地服务器并访问文件的简单过程。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值