-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserve-static.ts
60 lines (56 loc) · 1.74 KB
/
serve-static.ts
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
import * as fs from 'fs';
import { extname } from 'path';
const fastify = require('fastify')({ logger: true })
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm',
'.gz':'application/gzip'
};
const cache = {};
fastify.get('*', (_, reply) => {
try{
const filePath = extname(_.raw.url) ? './client/dist' + _.raw.url : './client/dist/index.html';
const ext = extname(filePath).toLowerCase();
let contentType = mimeTypes[ext] || 'application/octet-stream';
if (!cache[filePath]){
if (fs.existsSync(filePath))
cache[filePath] = {file:fs.readFileSync(filePath), type:contentType}
else {
cache[filePath] = {file:fs.readFileSync(filePath + '.gz'), type: mimeTypes['.gz']}
}
}
const file = cache[filePath];
if (file.type === mimeTypes['.gz']){
reply.header('Content-Encoding', 'gzip').type(file.type).send(file.file)
} else{
reply.type(file.type).send(file.file)
}
}
catch (e) {
console.log(e)
}
})
// Run the server!
const start = async () => {
try {
await fastify.listen(4200,'0.0.0.0')
fastify.log.info(`server listening on ${fastify.server.address().port}`)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()