Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
79 lines (69 loc) · 2.4 KB
/
Copy pathserver.js
File metadata and controls
79 lines (69 loc) · 2.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env node
const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = process.env.PORT || 3000;
const PUBLIC_DIR = __dirname;
const MIME_TYPES = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".ico": "image/x-icon",
".woff2": "font/woff2",
".woff": "font/woff",
".mp4": "video/mp4",
".rsc": "text/x-component"
};
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
let pathname = decodeURIComponent(url.pathname);
if (pathname === "/" || pathname === "/landing") {
pathname = "/index.html";
} else if (pathname === "/login" || pathname === "/login/") {
pathname = "/login/index.html";
}
if (url.searchParams.has("_rsc")) {
if (url.pathname.includes("landing") && fs.existsSync(path.join(PUBLIC_DIR, "landing.rsc"))) {
pathname = "/landing.rsc";
} else if (url.pathname.includes("login") && fs.existsSync(path.join(PUBLIC_DIR, "login.rsc"))) {
pathname = "/login.rsc";
}
}
const filePath = path.join(PUBLIC_DIR, pathname);
if (!filePath.startsWith(PUBLIC_DIR)) {
res.writeHead(403);
res.end("Forbidden");
return;
}
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
const indexPath = path.join(PUBLIC_DIR, "index.html");
if (fs.existsSync(indexPath)) {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
fs.createReadStream(indexPath).pipe(res);
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end(`Not Found: ${pathname}`);
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || "application/octet-stream";
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=3600",
"Content-Length": stats.size
});
fs.createReadStream(filePath).pipe(res);
});
});
server.listen(PORT, () => {
console.log(`\x1b[32m✔ SearchPoint (${path.basename(PUBLIC_DIR)}) static server running at:\x1b[0m`);
console.log(` \x1b[36mhttp://localhost:${PORT}/\x1b[0m\n`);
console.log(`Press Ctrl+C to stop.`);
});