Home > Web Front-end > JS Tutorial > An in-depth analysis of the koa-static middleware in nodejs

An in-depth analysis of the koa-static middleware in nodejs

青灯夜游
Release: 2021-03-08 10:05:24
forward
2398 people have browsed it

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.

An in-depth analysis of the koa-static middleware in nodejs

Related recommendations: "nodejs tutorial"

Details on the use of koa-static

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)
Copy after login

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
Copy after login
//引入
const server=require('koa-static')
Copy after login
//使用
app.use(server('static'))//或:app.use(server(__dirname+'/static'))
Copy after login

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" />
Copy after login

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;

  • ##Return to the browser through response Server

As mentioned earlier, the function of koa-static is ☞static file hosting☜, which is definitely not just for resource files such as CSS and JavaScript.

In fact, for images, koa-static can also be used to set

image cache! Just like this

const server=require(&#39;koa-static&#39;)
const path=require(&#39;path&#39;)   //path模块:设置路径信息

const staticPath=path.resolve(__dirname,&#39;static&#39;)
const staticServer=server(staticPath,{
	setHeadears:(res,path,stats)=>{
		if(path.indexOf(/[jpg|png|gif|jpeg]/)>-1){
			res.setHeader(&#39;Cache-Control&#39;,[&#39;private&#39;,&#39;max-age=60&#39;])
		}
	}
})
app.use(staticServer);
Copy after login

- If the corresponding path is an image in jpg/GIF/png/jpeg format, then it will be cached for 60s.


We all know that there is a "convenient way" for static services in express (node ​​framework):

app.use(&#39;/teacher&#39;,express.static(&#39;/public&#39;))
Copy after login

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(&#39;koa&#39;)
const server=require(&#39;koa-static&#39;)
const mount=require(&#39;koa-mount&#39;)

const app=new Koa()
app.use(mount(&#39;/teacher&#39;,server(&#39;/public&#39;)))
Copy after login

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.


Exploration of static principles

After learning the magical usage above, have you ever thought about how it is implemented?

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(&#39;koa-send&#39;);
//...
function serve (root, opts) {
	//...
	return async function serve (ctx, next) {
		await next()
		if (ctx.method !== &#39;HEAD&#39; && ctx.method !== &#39;GET&#39;) 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
			}
		}
	}
}
Copy after login

After this code, we found that the core implementation is the

send() method, and this is Provided by module koa-send!

Find the source code of koa-send and found that its core implementation principle is also very simple:

if (!ctx.type) ctx.type = type(path, encodingExt)
ctx.body = fs.createReadStream(path)
Copy after login

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:

  • Set the Content-Type, which can be set through the file suffix;

  • Assign value to ctx.body in Stream form

Why is it interesting?

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!

Let us compare the following code with the source code of koa-send above:

app.use(function(ctx){
	const fs=require(&#39;fs&#39;)
	const result=fs.readFileSync(&#39;xxx&#39;)
	ctx.type=type(result, encodingExt)
	ctx.body=result
})
Copy after login

Koa review

In fact, in koa, ctx.body The working principle is actually similar to the koa-static and koa-send middleware mentioned in this article:

Process different Content-types according to the assignment type

  • According to the body Type setting corresponding Content-type

  • Call res.write or res.end according to Content-type to write data to the browser

About

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!

More programming related For knowledge, please visit:

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template