koa-static源码解析

介绍

Koa static file serving middleware, wrapper for koa-send.

意为 Koa 静态文件服务中间件,使用koa-send包裹。

源码 koa-static 5.0.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
function serve(root, opts) {
// 拷贝一份传入的参数对象
opts = Object.assign(Object.create(null), opts);

// 将root解析为合法路径并设置到opts参数对象上
opts.root = resolve(root);

// 格式化路径,index设置则使用该路径否则默认使用index.html
if (opts.index !== false) opts.index = opts.index || "index.html";

// 判断是否需要延时执行
if (!opts.defer) {
return async function serve(ctx, next) {
// 该变量记录文件是否成功返回
let done = false;

// 判断只有HEAD和GET方法才响应
if (ctx.method === "HEAD" || ctx.method === "GET") {
try {
// 使用koa-send发送文件,如果成功则返回路径赋值给done
done = await send(ctx, ctx.path, opts);
} catch (err) {
// 判断请求的错误状态码,排除400,500等非预期错误
if (err.status !== 404) {
throw err;
}
}
}

// 如果请求文件失败,则执行后续中间件处理结果
// 如果请求文件成功,则该中间件运行到此为止
// 如果后续中间件有必须的处理,则设置defer参数或将该中间件置于末位
if (!done) {
await next();
}
};
}

return async function serve(ctx, next) {
// 如需延时执行,则调用next先处理后边的中间件
await next();

if (ctx.method !== "HEAD" && ctx.method !== "GET") return;

if (ctx.body != null || ctx.status !== 404) return;

try {
await send(ctx, ctx.path, opts);
} catch (err) {
if (err.status !== 404) {
throw err;
}
}
};
}

其实可以看到 Koa-static 没有做太多的逻辑,主要都是依托 send 库发送文件。

参考链接

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

给阿姨来一杯卡普基诺~

支付宝
微信