-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
59 lines (50 loc) · 1.27 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
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
}
/** @typedef {import("koa").Context} Context */
/**
* @param {Context} ctx - Koa Context
* @param {string} path - path of the file to send
* @returns {Promise<fs.Stats>}
*/
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
}
}