-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (67 loc) · 2.11 KB
/
server.js
File metadata and controls
80 lines (67 loc) · 2.11 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
80
const http = require("http");
const fs = require("fs");
const os = require("os");
const path = require("path");
const host = process.env.HOST || "0.0.0.0";
const port = Number(process.env.PORT) || 3000;
const publicDir = path.join(__dirname, "public");
const mimeTypes = {
".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",
".ico": "image/x-icon"
};
function sendFile(res, filePath) {
fs.readFile(filePath, (error, content) => {
if (error) {
res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Internal Server Error");
return;
}
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, {
"Content-Type": mimeTypes[ext] || "application/octet-stream; charset=utf-8"
});
res.end(content);
});
}
function getLanUrls() {
const networkInterfaces = os.networkInterfaces();
const urls = [];
Object.values(networkInterfaces).forEach((addresses) => {
(addresses || []).forEach((address) => {
if (address.family === "IPv4" && !address.internal) {
urls.push(`http://${address.address}:${port}`);
}
});
});
return urls;
}
const server = http.createServer((req, res) => {
const urlPath = req.url === "/" ? "/index.html" : req.url;
const safePath = path.normalize(urlPath).replace(/^(\.\.[/\\])+/, "");
const filePath = path.join(publicDir, safePath);
if (!filePath.startsWith(publicDir)) {
res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Forbidden");
return;
}
fs.stat(filePath, (error, stats) => {
if (error || !stats.isFile()) {
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not Found");
return;
}
sendFile(res, filePath);
});
});
server.listen(port, host, () => {
console.log("LocalTools running at:");
console.log(`- Local: http://127.0.0.1:${port}`);
getLanUrls().forEach((url) => {
console.log(`- Network: ${url}`);
});
});