forked from koajs/file-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
217 lines (173 loc) · 5.66 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
var compressible = require('compressible')
var resolve = require('resolve-path')
var hash = require('hash-stream')
var mime = require('mime-types')
var spdy = require('spdy-push')
var assert = require('assert')
var zlib = require('mz/zlib')
var Path = require('path')
var fs = require('mz/fs')
var extname = Path.extname
var basename = Path.basename
var methods = 'HEAD,GET,OPTIONS'
var 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()
var cache = Object.create(null)
var maxage = options.maxage
var cachecontrol = maxage != null
? ('public, max-age=' + (maxage / 1000 | 0))
: ''
var etagoptions = options.etag || {}
var algorithm = etagoptions.algorithm || 'sha256'
var encoding = etagoptions.encoding || 'base64'
var index = options.index
var 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
function* serve(next) {
this.fileServer = new FileServer(this)
yield* send(this, null, next);
}
// utility
function* send(ctx, path, next) {
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 = yield* get(path)
if (!file) { // 404
yield* next;
return;
}
// 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
function* get(path) {
//var val = cache[path]
//if (val && val.compress && (yield fs.exists(val.compress.path))) return val
var stats = yield 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 = {
stats: stats,
etag: '"' + (yield hash(path, algorithm)).toString(encoding) + '"',
type: mime.contentType(extname(path)) || 'application/octet-stream',
compress: false,
}
return file; // No gzipping here
}
}
function ignoreStatError(err) {
if (notfound[err.code]) return
err.status = 500
throw err
}
function leadingDot(path) {
return '.' === basename(path)[0]
}
function random() {
return Math.random().toString(36).slice(2)
}