Home >Web Front-end >JS Tutorial >An in-depth analysis of the koa-static middleware in nodejs
This article will introduce to you the static file middleware koa-static in node. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "nodejs tutorial"
in app.js Here, if we want to specify the current directory as a managed directory, we usually do this:
const static=require('koa-static') const Koa=require('koa') const app=new Koa() app.use(static('.')) app.listen(8081)
koa-static is the most commonly used and mature in koa (node framework) Static web hosting service middleware, commonly used in koa such as external link static resources (such as CSS files):
//下载 npm install koa-static --save
//引入 const server=require('koa-static')
//使用 app.use(server('static'))//或:app.use(server(__dirname+'/static'))
In short, the server must have a static template (relative) path
Then we can use the xxx.css file in the css folder in the static directory like this:
<link rel="stylesheet" href="css/xxx.css" />
Is it that simple? So what is its principle?
Set the request header "Content-Type" value according to the file suffix name to match the browser rendering!
Let’s take the static mentioned above:
Look for static/css/xxx.css
to see if it exists
(if exists)Set Content-Type: text/css;charset=utf-8;
image cache! Just like this
const server=require('koa-static') const path=require('path') //path模块:设置路径信息 const staticPath=path.resolve(__dirname,'static') const staticServer=server(staticPath,{ setHeadears:(res,path,stats)=>{ if(path.indexOf(/[jpg|png|gif|jpeg]/)>-1){ res.setHeader('Cache-Control',['private','max-age=60']) } } }) app.use(staticServer);- If the corresponding path is an image in jpg/GIF/png/jpeg format, then it will be cached for 60s.
app.use('/teacher',express.static('/public'))It can specify the "request prefix" of static services —— It is to specify the static resource relative to which URL to load. Obviously, this is very practical. We suddenly thought that the koa-static we mentioned above in this article all works relative to "
global"?
How to implement this function in koa? koa provides another (auxiliary) module for developers -koa-mount
const Koa=require('koa') const server=require('koa-static') const mount=require('koa-mount') const app=new Koa() app.use(mount('/teacher',server('/public')))
koa-mount is a Koa middleware that mounts middleware to a specified path . It can mount any Koa middleware!As mentioned before, koa-static is a middleware, so koa-mount can be combined with koa-static to achieve the same static service request prefix function as express.
Through
npm info koa-static, you will find that koa-static depends on two modules, namely debug and koa-send.
Find the index file of the koa-static source code. Its core implementation is as follows:
const send = require('koa-send'); //... function serve (root, opts) { //... return async function serve (ctx, next) { await next() if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return if (ctx.body !== null && ctx.status !== 404) return // eslint-disable-line try { await send(ctx, ctx.path, opts) }catch (err) { if (err.status !== 404) { throw err } } } }After this code, we found that the core implementation is the
send() method, and this is Provided by module
koa-send!
if (!ctx.type) ctx.type = type(path, encodingExt) ctx.body = fs.createReadStream(path)The type method is set according to the file suffix
Content-Type! Very practical, but what we should pay more attention to here is another interesting thing - the principle of koa-send:
In addition to the fact that it also aims at setting content-type, the stream method has always been praised by industry leaders: because it is more efficient than
fs.readFileSync!
app.use(function(ctx){ const fs=require('fs') const result=fs.readFileSync('xxx') ctx.type=type(result, encodingExt) ctx.body=result })
Process different Content-types according to the assignment type
AboutMore programming related For knowledge, please visit:Content-type value: String - divided into two types (different): "text/html" and "text/plain";
Buffer / Stream Type;
If it is not any of the above types, then it should be a JSON object
(In the source code, typeof is used to determine its type. This technique is very practical!
programming video!!
The above is the detailed content of An in-depth analysis of the koa-static middleware in nodejs. For more information, please follow other related articles on the PHP Chinese website!