This repository was archived by the owner on Nov 22, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic-server.mjs
More file actions
executable file
·65 lines (58 loc) · 1.85 KB
/
static-server.mjs
File metadata and controls
executable file
·65 lines (58 loc) · 1.85 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
#!/usr/bin/env node
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
const [, , rootArg, portArg] = process.argv;
if (!rootArg || !portArg) {
console.error('Usage: node tools/static-server.mjs <dir> <port>');
process.exit(1);
}
const ROOT = path.resolve(process.cwd(), rootArg);
const PORT = parseInt(portArg, 10);
if (isNaN(PORT) || PORT < 1 || PORT > 65535) {
console.error('Invalid port number');
process.exit(1);
}
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.wasm': 'application/wasm',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.txt': 'text/plain; charset=utf-8'
};
const server = http.createServer((req, res) => {
const urlPath = decodeURIComponent(req.url.split('?')[0]);
let filePath = path.join(ROOT, urlPath);
if (filePath.endsWith('/')) filePath += 'index.html';
// Prevent path traversal by ensuring filePath is within ROOT
const relative = path.relative(ROOT, filePath);
if (relative.startsWith('..') || path.isAbsolute(relative)) {
res.statusCode = 403;
res.end('Forbidden');
return;
}
fs.stat(filePath, (err, stat) => {
if (err || !stat.isFile()) {
res.statusCode = 404;
res.end('Not found');
return;
}
const ext = path.extname(filePath).toLowerCase();
res.setHeader('Content-Type', MIME[ext] || 'application/octet-stream');
fs.createReadStream(filePath)
.on('error', () => {
res.statusCode = 500;
res.end('Error reading file');
})
.pipe(res);
});
});
server.listen(PORT, () => {
console.log(`Static server running at http://localhost:${PORT}`);
console.log(`Serving files from: ${ROOT}`);
});