-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
88 lines (79 loc) · 2.22 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const http = require("http");
const fs = require("fs");
const path = require("path");
let WebSocket;
try {
WebSocket = require("ws");
} catch (error) {
console.log("You have not installed ws, hot reload will not work!\n");
}
const port = process.env.PORT || 1080;
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, "", req.url === "/" ? "index.html" : req.url);
const extname = path.extname(filePath);
let contentType = "text/html";
switch (extname) {
case ".js":
contentType = "text/javascript";
break;
case ".css":
contentType = "text/css";
break;
case ".png":
contentType = "image/png";
break;
case ".jpg":
contentType = "image/jpg";
break;
case ".ico":
contentType = "image/x-ico";
break;
case ".svg":
contentType = "image/svg";
break;
}
const extensions = [".js", ".css", ".png", ".jpg", ".ico", ".svg"];
let dest = extensions.find(() => extname) == undefined || req.url == "/" ? "index.html" : req.url;
let pCount = 0;
for(d of dest){
if(d=="."){pCount++};
if(pCount>1){
res.writeHead(400, { "Content-Type": "text/plain" });
res.end();
return
}
}
fs.readFile(path.join(__dirname, dest), (err, data) => {
if (err) {
res.writeHead(err.code == "ENOENT" ? 404 : 400, { "Content-Type": "text/plain" });
res.end(err.message ? err.message : err);
return;
}
res.writeHead(200, { "Content-Type": contentType });
res.end(data, "utf8");
});
});
if (WebSocket) {
const wss = new WebSocket.Server({ server });
function watchDirectory(directoryPath) {
fs.watch(directoryPath, (eventType, filename) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send("reload");
}
});
});
const files = fs.readdirSync(directoryPath);
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
watchDirectory(filePath);
}
});
}
watchDirectory("./src");
}
server.listen(port, () => {
console.log(`server running at http://localhost:${port}`);
});