-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
52 lines (44 loc) · 1.1 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
const promisify = require('util').promisify
const extname = require('path').extname
const fs = require('fs')
const calculate = require('etag')
const stat = promisify(fs.stat)
const notfound = {
ENOENT: true,
ENAMETOOLONG: true,
ENOTDIR: true
}
module.exports = async function sendfile (ctx, path) {
try {
const stats = await stat(path)
if (!stats) return null
if (!stats.isFile()) return stats
ctx.response.status = 200
ctx.response.lastModified = stats.mtime
ctx.response.length = stats.size
ctx.response.type = extname(path)
if (!ctx.response.etag) {
ctx.response.etag = calculate(stats, {
weak: true
})
}
// fresh based solely on last-modified
switch (ctx.request.method) {
case 'HEAD':
ctx.status = ctx.request.fresh ? 304 : 200
break
case 'GET':
if (ctx.request.fresh) {
ctx.status = 304
} else {
ctx.body = fs.createReadStream(path)
}
break
}
return stats
} catch (err) {
if (notfound[err.code]) return
err.status = 500
throw err
}
}