-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
66 lines (59 loc) · 1.76 KB
/
Copy pathserver.mjs
File metadata and controls
66 lines (59 loc) · 1.76 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
import http from "http";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = Number(process.env.PORT) || 3000;
const MIME = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".ico": "image/x-icon",
".svg": "image/svg+xml",
};
function safePath(urlPath) {
const decoded = decodeURIComponent(urlPath.split("?")[0]);
const rel = decoded === "/" ? "/index.html" : decoded;
const resolved = path.normalize(path.join(__dirname, rel));
if (!resolved.startsWith(__dirname)) return null;
return resolved;
}
function requestHandler(req, res) {
const filePath = safePath(req.url ?? "/");
if (!filePath) {
res.writeHead(403);
res.end("Forbidden");
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(err.code === "ENOENT" ? 404 : 500);
res.end(err.code === "ENOENT" ? "Not found" : "Server error");
return;
}
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, { "Content-Type": MIME[ext] ?? "application/octet-stream" });
res.end(data);
});
}
function start(port) {
const server = http.createServer(requestHandler);
server.on("error", (err) => {
if (err.code === "EADDRINUSE" && port < 3010) {
start(port + 1);
return;
}
console.error(err.message);
process.exit(1);
});
server.listen(port, () => {
console.log(`Base0km çalışıyor: http://localhost:${port}`);
console.log("Durdurmak için Ctrl+C");
});
}
start(PORT);