Repository navigation
Expand file tree
/
Copy pathdev-server.mjs
More file actions
49 lines (46 loc) · 1.76 KB
/
Copy pathdev-server.mjs
File metadata and controls
49 lines (46 loc) · 1.76 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
// Zero-dependency static file server for local development.
// ES module workers and relative-path assets require http:// — opening
// index.html from file:// will not run workers, so use `npm run dev`.
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join, normalize, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('.', import.meta.url));
const base = join(root, process.argv[2] ?? '.');
const port = Number(process.env.PORT ?? 8080);
const host = process.env.HOST ?? '127.0.0.1';
const MIME = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.txt': 'text/plain; charset=utf-8',
};
createServer(async (req, res) => {
try {
// Strip the query, normalize, and refuse anything that escapes the root.
let path = decodeURIComponent(new URL(req.url, 'http://x').pathname);
if (path.endsWith('/')) path += 'index.html';
const file = normalize(join(base, path));
if (!file.startsWith(base + sep) && file !== base) {
res.writeHead(403).end('forbidden');
return;
}
const body = await readFile(file);
res.writeHead(200, {
'content-type': MIME[extname(file)] ?? 'application/octet-stream',
'cache-control': 'no-store',
});
res.end(body);
} catch {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.end('404 — not found');
}
}).listen(port, host, () => {
console.log(`Diffbench dev server → http://localhost:${port}/`);
});