koa-static 源码分析
koa-static
koa-static
是 koa 的静态文件服务中间件
Example
1 |
|
比如你的static
文件目录结构为
1 |
|
那就可以通过浏览器访问http://localhost:8888/html/upfile.html
访问静态文件了
options
截取自koa-static
github readme 的常用 options
maxage
Browser cache max-age in milliseconds. defaults to 0hidden
Allow transfer of hidden files. defaults to falseindex
Default file name, defaults to ‘index.html’defer
If true, serves afterreturn next()
, allowing any downstream middleware to respond first.gzip
Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.- [setHeaders] Function to set custom headers on response.
extensions
Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults tofalse
)
源码分析
koa-static
依赖koa-send
包, 大部分逻辑都是koa-send
处理的, koa-static
只对options.defer
做了处理.
- defer 顾名思义, 如果为
true
, 则先执行koa-send
, 找到文件直接返回, 否则await next()
;false
则相反, 先await next()
,ctx.body
如果还是null
则执行koa-send
koa-send
核心逻辑通过path.resolvePath(ctx.path)
和初始化时的 root 路径拼接得到文件在服务端的真实文件路径, 最后以 readable stream 的形式返回
1 |
|
koa 中同样对 stream 类型的数据做了处理, 通过pipe
管道返回给浏览器数据
1 |
|
koa-static
也通过fs.stat
获取文件的具体信息设置响应头
1 |
|
对 option.setHeader 的处理
1 |
|
对 option.hidden 的处理, 这里 option.hidden 为 true 以及文件名以.
开头都是会隐藏的, isHidden
函数判断文件名是否为.xxx
1 |
|
对 option.extensions 的处理, 设置了 extensions 数组则允许浏览器 url 不带上后缀
1 |
|
koa-static 源码分析
https://mariana-yui.github.io/2022/08/20/2022-08-20-koa-static/