当前位置: 首页 > 后端技术 > Node.js

koa(http[301],http[304],实现静态文件服务状态的例子

时间:2023-04-03 15:52:42 Node.js

目的是学习http状态码githubL6zt自己的原git地址gitclonehttps://github.com/L6zt/httpS...npminstallnodeindex看console/*borhter,看http解释对应的responseheaderboreher,对应操作看nodekoa文档,我很好*/constkoa=require('koa')const$path=require('path')constfs=require('fs');constmime=require('mime');constapp=newkoa();letdefaultPort=8080//返回文件内容bufferconstfindAndReturnFile=async(fileName)=>{returnawaitnewPromise((r,j)=>{fs.readFile(fileName,//{encoding:'utf-8'},(err,data)=>{if(err){returnj(err)}else{r(data)}})})}//getgmttimestampconstgetUtmTimestamp=(date)=>newDate(date).toUTCString()//获取文件描述constfindAndReturnFileDesc=async(fileName)=>{constfd=awaitnewPromise((r,j)=>{fs.open(文件名,'r',(err,fd)=>{if(err){returnj(err)}else{r(fd)}})})conststat=awaitnewPromise((r,j)=>{fs.fstat(fd,(err,stat)=>{if(err){returnj(err)}r(stat)fs.close(fd,(err)=>{if(err)j(err)})})})returnstat}app.use(async(ctx,next)=>{awaitnext()console.log('你有小女孩吗?');})app.use(async(ctx)=>{const{response}=ctx;let{path}=ctx//案例模拟重定向if(/^\/301*?/.test(path)){ctx.response.status=301ctx.response.set({//重定向地址位置:'https://baidu.com'})ctx.body='耐心等待'return}//200---模拟koa的静态服务if(/assets\/.*/.test(path)){path=path.replace(/^assets\//,'')constfilePath=$path.join(__dirname,路径)constfileMime=mime.getType(path.split('.').pop())ctx.status=200const{mtime}=awaitfindAndReturnFileDesc(filePath)constresult=awaitfindAndReturnFile(filePath)const{'if-modified-since':ifModifiedSinceDate}=ctx.headersconstLastModifiedDate=getUtmTimestamp(mtime);//304if(LastModifiedDate===ifModifiedSinceDate){ctx.status=304return}ctx.set({'Content-Type':fileMime,'Xserver':'xBykoa','Last-Modified':LastModifiedDate})ctx.body=结果;}})conststartKoadApp=(port)=>newPromise((r,j)=>app.listen(port,(err)=>{if(err){j(prot+1)}else{constprefix=`http://localhost:${defaultPort}`console.log('***-服务器-***');console.log(`${prefix}/301`,'感受301吧')console.日志(`${prefix}/assets/**.ext`,'感受获取静态资源的服务');console.log(`${prefix}/assets/index.html`);console.log('***--***');}}));startKoadApp(defaultPort).catch(e=>{defaultPort++startKoadApp(defaultPort)})