-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
231 lines (194 loc) · 6.33 KB
/
index.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
var crypto = require('crypto')
var fs = require('mz/fs')
var zlib = require('mz/zlib')
var path = require('path')
var mime = require('mime-types')
var compressible = require('compressible')
var readDir = require('fs-readdir-recursive')
var debug = require('debug')('koa-static-cache')
module.exports = function staticCache(dir, options, files) {
if (typeof dir === 'object') {
files = options
options = dir
dir = null
}
options = options || {}
// prefix must be ASCII code
options.prefix = (options.prefix || '').replace(/\/*$/, '/')
files = new FileManager(files || options.files)
dir = dir || options.dir || process.cwd()
dir = path.normalize(dir)
var enableGzip = !!options.gzip
var filePrefix = path.normalize(options.prefix.replace(/^\//, ''))
// option.filter
var fileFilter = function () { return true }
if (Array.isArray(options.filter)) fileFilter = function (file) { return ~options.filter.indexOf(file) }
if (typeof options.filter === 'function') fileFilter = options.filter
if (options.preload !== false) {
readDir(dir).filter(fileFilter).forEach(function (name) {
loadFile(name, dir, options, files)
})
}
return async (ctx, next) => {
// only accept HEAD and GET
if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return await next()
// decode for `/%E4%B8%AD%E6%96%87`
// normalize for `//index`
var filenameRaw = safeDecodeURIComponent(ctx.path)
var filename = path.normalize(filenameRaw)
// check alias
if (options.alias && options.alias[filenameRaw]) {
filenameRaw = options.alias[filenameRaw]
filename = path.normalize(filenameRaw)
}
// check prefix first to avoid calculate
if (filenameRaw.indexOf(options.prefix) !== 0) return await next()
var file = files.get(filename)
// try to load file
if (!file) {
if (!options.dynamic) return await next()
if (path.basename(filename)[0] === '.') return await next()
if (filename.charAt(0) === path.sep) filename = filename.slice(1)
// trim prefix
if (options.prefix !== '/') {
if (filename.indexOf(filePrefix) !== 0) return await next()
filename = filename.slice(filePrefix.length)
}
// by zhennann
var fullpath;
if(options.getFullPath) {
fullpath = options.getFullPath(ctx, dir, filename, options)
if(!fullpath) {
return await next()
}
} else {
fullpath = path.join(dir, filename)
// files that can be accessd should be under options.dir
if (fullpath.indexOf(dir) !== 0) {
return await next()
}
}
var s
try {
s = await fs.stat(fullpath)
} catch (err) {
return await next()
}
if (!s.isFile()) return await next()
file = loadFile(filename, dir, options, files, fullpath)
}
ctx.status = 200
if (enableGzip) ctx.vary('Accept-Encoding')
if (!file.buffer) {
var stats = await fs.stat(file.path)
if (stats.mtime.getTime() !== file.mtime.getTime()) {
file.mtime = stats.mtime
file.md5 = null
file.length = stats.size
}
}
ctx.response.lastModified = file.mtime
if (file.md5) ctx.response.etag = file.md5
if (ctx.fresh) return ctx.status = 304
ctx.type = file.type
ctx.length = file.zipBuffer ? file.zipBuffer.length : file.length
ctx.set('cache-control', file.cacheControl || 'public, max-age=' + file.maxAge)
if (file.md5) ctx.set('content-md5', file.md5)
if (ctx.method === 'HEAD') return
var acceptGzip = ctx.acceptsEncodings('gzip') === 'gzip'
if (file.zipBuffer) {
if (acceptGzip) {
ctx.set('content-encoding', 'gzip')
ctx.body = file.zipBuffer
} else {
ctx.body = file.buffer
}
return
}
var shouldGzip = enableGzip
&& file.length > 1024
&& acceptGzip
&& compressible(file.type)
if (file.buffer) {
if (shouldGzip) {
var gzFile = files.get(filename + '.gz')
if (options.usePrecompiledGzip && gzFile && gzFile.buffer) { // if .gz file already read from disk
file.zipBuffer = gzFile.buffer
} else {
file.zipBuffer = await zlib.gzip(file.buffer)
}
ctx.set('content-encoding', 'gzip')
ctx.body = file.zipBuffer
} else {
ctx.body = file.buffer
}
return
}
var stream = fs.createReadStream(file.path)
// update file hash
if (!file.md5) {
var hash = crypto.createHash('md5')
stream.on('data', hash.update.bind(hash))
stream.on('end', function () {
file.md5 = hash.digest('base64')
})
}
ctx.body = stream
// enable gzip will remove content length
if (shouldGzip) {
ctx.remove('content-length')
ctx.set('content-encoding', 'gzip')
ctx.body = stream.pipe(zlib.createGzip())
}
}
}
function safeDecodeURIComponent(text) {
try {
return decodeURIComponent(text)
} catch (e) {
return text
}
}
/**
* load file and add file content to cache
*
* @param {String} name
* @param {String} dir
* @param {Object} options
* @param {Object} files
* @return {Object}
* @api private
*/
function loadFile(name, dir, options, files, fullpath) {
var pathname = path.normalize(path.join(options.prefix, name))
if (!files.get(pathname)) files.set(pathname, {})
var obj = files.get(pathname)
var filename = obj.path = fullpath // path.join(dir, name)
var stats = fs.statSync(filename)
var buffer = fs.readFileSync(filename)
obj.cacheControl = options.cacheControl
obj.maxAge = obj.maxAge ? obj.maxAge : options.maxAge || 0
obj.type = obj.mime = mime.lookup(pathname) || 'application/octet-stream'
obj.mtime = stats.mtime
obj.length = stats.size
obj.md5 = crypto.createHash('md5').update(buffer).digest('base64')
debug('file: ' + JSON.stringify(obj, null, 2))
if (options.buffer)
obj.buffer = buffer
buffer = null
return obj
}
function FileManager(store) {
if (store && typeof store.set === 'function' && typeof store.get === 'function') {
this.store = store
} else {
this.map = store || Object.create(null)
}
}
FileManager.prototype.get = function (key) {
return this.store ? this.store.get(key) : this.map[key]
}
FileManager.prototype.set = function (key, value) {
if (this.store) return this.store.set(key, value)
this.map[key] = value
}