-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
56 lines (49 loc) · 1.75 KB
/
Copy pathserver.js
File metadata and controls
56 lines (49 loc) · 1.75 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
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { extname, relative, resolve } from "node:path";
const port = Number(process.env.PORT || 4173);
const root = process.cwd();
const contentTypes = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".txt": "text/plain; charset=utf-8",
".xml": "application/xml; charset=utf-8",
".json": "application/json; charset=utf-8",
".ico": "image/x-icon",
".png": "image/png",
".webmanifest": "application/manifest+json; charset=utf-8",
".svg": "image/svg+xml"
};
const server = createServer(async (request, response) => {
let filePath;
try {
const url = new URL(request.url ?? "/", `http://${request.headers.host}`);
const requestedPath = url.pathname === "/" ? "/index.html" : url.pathname;
filePath = resolve(root, `.${decodeURIComponent(requestedPath)}`);
} catch {
response.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
response.end("Bad request");
return;
}
try {
const relativePath = relative(root, filePath);
if (relativePath.startsWith("..") || relativePath === "" || resolve(relativePath) === relativePath) {
response.writeHead(403);
response.end("Forbidden");
return;
}
const body = await readFile(filePath);
response.writeHead(200, {
"content-type": contentTypes[extname(filePath)] ?? "application/octet-stream",
"cache-control": "no-store"
});
response.end(body);
} catch {
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
response.end("Not found");
}
});
server.listen(port, () => {
console.log(`Manhole card map running at http://localhost:${port}`);
});