-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
77 lines (66 loc) · 1.94 KB
/
index.js
File metadata and controls
77 lines (66 loc) · 1.94 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const {extend} = require('lodash')
const parseUrl = require('./lib/parseUrl')
const validate = require('./lib/validate')
const sendFile = require('./lib/sendFile')
const cache = sendFile.cache
const debug = require('debug')('koa-file-server')
module.exports = (root, options) => {
if (typeof root === 'object') {
options = root
root = null
}
options = extend({
root: process.cwd(),
webp: true,
identifier: '??',
maxAge: 60 * 60 * 24 * 30,
cache: {
dirName: '__cache',
maxAge: 1000 * 60 * 60,
maxSize: 1024 * 1024 * 500
},
compress: [
'application/javascript',
'application/rss+xml',
'application/vnd.ms-fontobject',
'application/x-font',
'application/x-font-opentype',
'application/x-font-otf',
'application/x-font-truetype',
'application/x-font-ttf',
'application/x-javascript',
'application/xhtml+xml',
'application/xml',
'font/opentype',
'font/otf',
'font/ttf',
'image/svg+xml',
'image/x-icon',
'text/css',
'text/html',
'text/javascript',
'text/plain',
'text/xml'
]
}, options)
root = root || options.root
cache.__init(options.cache)
return async function serve (ctx, next) {
await next()
// 请求过滤
if (!/^GET|HEAD$/.test(ctx.method) || ctx.status !== 404 || ctx.body) return
// 解析请求
let request = parseUrl(root, options, decodeURIComponent(ctx.url), ctx.request.header.accept)
// 解析成功验证文件是否存在
if (/^20[0-7]$/.test(request.status)) request = await validate(root, request)
debug('解析结束:' + JSON.stringify(request, null, 4))
// 请求状态
ctx.status = request.status
if (/^20[0-7]$/.test(request.status)) {
sendFile(ctx, request.body, options)
} else if (/^400|500$/.test(request.status)) {
ctx.body = request.body.error
}
}
}
module.exports.staticCache = cache