This repository was archived by the owner on Aug 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathstatic.js
62 lines (55 loc) · 1.9 KB
/
static.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
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const uWS = require('uWebSockets.js');
/** @param {string} dir */
const walkDir = dir => {
/** @type {string[]} */
let results = [];
const list = fs.readdirSync(dir);
list.forEach(file => {
file = path.join(dir, file);
const stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
/* Recurse into a subdirectory */
results = results.concat(walkDir(file));
} else {
/* Is a file */
results.push(file);
}
});
return results;
};
// Load files into memory
const buffers = new Map();
const publicRoot = path.resolve(__dirname, 'public');
const dir = walkDir(publicRoot).map(f => f.replace(publicRoot, '').replace(/\\/g, '/'));
for (const f of dir) {
buffers.set(f.replace(/\.html$/, '').replace(/\/index$/, '') || '/', {
mime: mime.lookup(f),
buffer: fs.readFileSync(path.resolve(publicRoot, ...f.split('/'))),
});
}
uWS.App()
.get('/*', (res, req) => {
const url = req.getUrl();
if (buffers.has(url)) {
const { mime, buffer } = buffers.get(url);
if (mime) res.writeHeader('content-type', mime);
res.writeHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.writeHeader('Cross-Origin-Embedder-Policy', 'require-corp');
if (mime === 'text/html') {
res.writeHeader('cache-control', 's-maxage=0,max-age=60');
} else {
res.writeHeader('cache-control', 's-maxage=86400,max-age=86400');
}
res.end(buffer);
} else {
res.writeStatus('302');
res.writeHeader('location', '/');
res.end();
}
})
.listen(8080, sock =>
console.log(sock ? 'Serving on port 8080' : 'Failed to listen on port 8080'),
);