-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.mjs
More file actions
55 lines (51 loc) · 1.78 KB
/
Copy pathserve.mjs
File metadata and controls
55 lines (51 loc) · 1.78 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
#!/usr/bin/env node
/**
* Minimal static file server for local previews.
* npm run serve → http://localhost:8080
*
* Resolves "/blog/" style directory URLs to their index.html so the site
* behaves the same way GitHub Pages does.
*/
import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import { join, extname, normalize } from 'node:path';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const PORT = process.env.PORT || 8080;
const TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.xml': 'application/xml; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
};
createServer(async (req, res) => {
try {
let urlPath = decodeURIComponent(new URL(req.url, `http://localhost`).pathname);
let filePath = normalize(join(ROOT, urlPath));
if (!filePath.startsWith(ROOT)) {
res.writeHead(403).end('Forbidden');
return;
}
let info = await stat(filePath).catch(() => null);
if (info && info.isDirectory()) {
filePath = join(filePath, 'index.html');
info = await stat(filePath).catch(() => null);
}
if (!info) {
res.writeHead(404, { 'Content-Type': 'text/html' }).end('<h1>404</h1>');
return;
}
const body = await readFile(filePath);
res.writeHead(200, { 'Content-Type': TYPES[extname(filePath)] || 'application/octet-stream' });
res.end(body);
} catch (err) {
res.writeHead(500).end('Server error');
}
}).listen(PORT, () => {
console.log(`Serving ${ROOT}\n → http://localhost:${PORT}/\n → http://localhost:${PORT}/blog/`);
});