This repository was archived by the owner on Aug 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkoa-file-server.js
213 lines (169 loc) · 5.03 KB
/
koa-file-server.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
'use strict'
const resolve = require('resolve-path')
const hash = require('hash-stream')
const mime = require('mime-types')
const spdy = require('spdy-push')
const assert = require('assert')
const Path = require('path')
const fs = require('mz/fs')
const extname = Path.extname
const basename = Path.basename
const methods = 'HEAD,GET,OPTIONS'
const notfound = {
ENOENT: true,
ENAMETOOLONG: true,
ENOTDIR: true
}
module.exports = function (root, options) {
if (typeof root === 'object') {
options = root
root = null
}
options = options || {}
root = root || options.root || process.cwd()
const cache = Object.create(null)
const maxage = options.maxage
const cachecontrol = maxage != null
? ('public, max-age=' + (maxage / 1000 | 0))
: ''
const etagoptions = options.etag || {}
const algorithm = etagoptions.algorithm || 'sha256'
const encoding = etagoptions.encoding || 'base64'
const index = options.index
const hidden = options.hidden
// this.fileServer.send(), etc.
function FileServer (context) {
this.context = context
}
FileServer.prototype.send = function* (path) {
return yield * send(this.context, path)
}
FileServer.prototype.push = function* (path, opts) {
return yield * push(this.context, path, opts)
}
serve.send = send
serve.push = push
serve.cache = cache
return serve
// middleware
async function serve (ctx, next) {
ctx.fileServer = new FileServer(ctx)
await next()
// response is handled
if (ctx.response.body) return
if (ctx.response.status !== 404) return
await send(ctx)
}
// utility
async function send (ctx, path) {
var req = ctx.request
var res = ctx.response
path = path || req.path.slice(1) || ''
// index file support
var directory = path === '' || path.slice(-1) === '/'
if (index && directory) path += 'index.html'
// regular paths can not be absolute
path = resolve(root, path)
// hidden file support
if (!hidden && leadingDot(path)) return
var file = await get(path)
if (!file) return // 404
// proper method handling
var method = req.method
switch (method) {
case 'HEAD':
case 'GET':
break // continue
case 'OPTIONS':
res.set('Allow', methods)
res.status = 204
return file
default:
res.set('Allow', methods)
res.status = 405
return file
}
res.status = 200
res.etag = file.etag
res.lastModified = file.stats.mtime
res.type = file.type
if (cachecontrol) res.set('Cache-Control', cachecontrol)
if (req.fresh) {
res.status = 304
return file
}
if (method === 'HEAD') return file
if (file.compress && req.acceptsEncodings('gzip', 'identity') === 'gzip') {
res.set('Content-Encoding', 'gzip')
res.length = file.compress.stats.size
res.body = fs.createReadStream(file.compress.path)
} else {
res.set('Content-Encoding', 'identity')
res.length = file.stats.size
res.body = fs.createReadStream(path)
}
return file
}
function* push (ctx, path, opts) {
assert(path, 'you must define a path!')
if (!ctx.res.isSpdy) return
opts = opts || {}
assert(path[0] !== '/', 'you can only push relative paths')
var uri = path // original path
// index file support
var directory = path === '' || path.slice(-1) === '/'
if (index && directory) path += 'index.html'
// regular paths can not be absolute
path = resolve(root, path)
var file = yield * get(path)
assert(file, 'can not push file: ' + uri)
var options = {
path: '/' + uri,
priority: opts.priority
}
var headers = options.headers = {
'content-type': file.type,
etag: file.etag,
'last-modified': file.stats.mtime.toUTCString()
}
if (cachecontrol) headers['cache-control'] = cachecontrol
if (file.compress) {
headers['content-encoding'] = 'gzip'
headers['content-length'] = file.compress.stats.size
options.filename = file.compress.path
} else {
headers['content-encoding'] = 'identity'
headers['content-length'] = file.stats.size
options.filename = path
}
spdy(ctx.res)
.push(options)
.send()
.catch(ctx.onerror)
return file
}
// get the file from cache if possible
async function get (path) {
var val = cache[path]
if (val && val.compress && (await fs.exists(val.compress.path))) return val
var stats = await fs.stat(path).catch(ignoreStatError)
// we don't want to cache 404s because
// the cache object will get infinitely large
if (!stats || !stats.isFile()) return
stats.path = path
var file = cache[path] = {
stats: stats,
etag: '"' + (await hash(path, algorithm)).toString(encoding) + '"',
type: mime.contentType(extname(path)) || 'application/octet-stream'
}
return file
}
}
function ignoreStatError (err) {
if (notfound[err.code]) return
err.status = 500
throw err
}
function leadingDot (path) {
return basename(path)[0] === '.'
}