Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
71 lines (62 loc) · 1.66 KB
/
Copy pathindex.js
File metadata and controls
71 lines (62 loc) · 1.66 KB
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
'use strict'
const glob = require('glob')
const statSync = require('fs').statSync
const send = require('send')
const fp = require('fastify-plugin')
function getDirFiles (src) {
return new Promise(function (resolve, reject) {
glob(`**/*`, {nodir: true, cwd: src}, (err, files) => {
if (err) {
return reject(err)
}
resolve(files)
})
})
}
async function plugin (fastify, opts, next) {
const error = checkOptions(opts)
if (error instanceof Error) {
return next(error)
}
const {root, prefix = ''} = opts
try {
const files = await getDirFiles(root)
files.forEach(filePath => {
const route = `${prefix}/${filePath}`.replace(/\/\//g, '/')
fastify.get(route, function (req, reply) {
pumpSendToReply(req, reply, filePath)
})
if (filePath.match(/index\.html$/)) {
fastify.get(route.replace(/index\.html$/, ''), function (req, reply) {
pumpSendToReply(req, reply, filePath)
})
}
})
} catch (err) {
return next(err)
}
fastify.decorateReply('sendFile', function (filePath) {
pumpSendToReply(this._req, this, filePath)
})
function pumpSendToReply (req, reply, pathname) {
const sendStream = send(req, pathname, {root})
sendStream.on('error', err => { throw err })
sendStream.pipe(reply.res)
}
next()
}
function checkOptions (opts) {
if (typeof opts.root !== 'string') {
return new Error('"root" option is required')
}
let rootStat
try {
rootStat = statSync(opts.root)
} catch (e) {
return e
}
if (!rootStat.isDirectory()) {
return new Error('"root" option must be an absolute path')
}
}
module.exports = fp(plugin)