Repository navigation
Expand file tree
/
Copy pathserve.js
More file actions
48 lines (42 loc) · 1.4 KB
/
Copy pathserve.js
File metadata and controls
48 lines (42 loc) · 1.4 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
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.dirname(fileURLToPath(import.meta.url));
const port = Number(process.argv[2]) || Number(process.env.PORT) || 4175;
const types = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.png': 'image/png',
'.webp': 'image/webp',
'.txt': 'text/plain; charset=utf-8',
};
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${port}`);
let rel = decodeURIComponent(url.pathname);
if (rel.endsWith('/')) rel += 'index.html';
const filePath = path.join(root, rel);
// Keep requests inside the project directory.
if (!filePath.startsWith(root)) {
res.writeHead(403).end('Forbidden');
return;
}
try {
const body = await readFile(filePath);
res.writeHead(200, {
'content-type': types[path.extname(filePath)] ?? 'application/octet-stream',
'cache-control': 'no-store',
});
res.end(body);
} catch {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.end('Not found');
}
});
server.listen(port, () => {
console.log(`Downforce running at http://localhost:${port}`);
});