-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
72 lines (64 loc) · 1.96 KB
/
server.js
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
const http = require("http");
const fs = require("fs");
const WebSocket = require("ws");
const path = require("path");
// Define the port
const PORT = 5000;
const serveStaticFile = (filePath, contentType, res) => {
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 Not Found");
} else {
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
}
});
};
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
const indexPath = path.resolve(__dirname, "index.html");
serveStaticFile(indexPath, "text/html", res);
} else if (req.method === "GET" && req.url.startsWith("/static/")) {
const filePath = path.resolve(__dirname, "." + req.url);
const ext = path.extname(filePath);
let contentType = "text/plain";
switch (ext) {
case ".js":
contentType = "application/javascript";
break;
case ".css":
contentType = "text/css";
break;
case ".html":
contentType = "text/html";
break;
}
serveStaticFile(filePath, contentType, res);
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 Not Found");
}
});
const wss = new WebSocket.Server({ server });
function listenOnChange(filePath) {
fs.watch(filePath, (eventType, filename) => {
if (eventType === "change") {
console.log(filePath, "has been modified.");
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send("refresh");
}
});
}
});
}
listenOnChange(path.resolve(__dirname, "static", "index.js"));
listenOnChange(path.resolve(__dirname, "static", "index.css"));
listenOnChange(path.resolve(__dirname, "index.html"));
wss.on("connection", (ws) => {
console.log("Client connected");
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});