-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
113 lines (99 loc) · 3.77 KB
/
server.js
File metadata and controls
113 lines (99 loc) · 3.77 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import http from "http";
import fs from "fs";
import { WebSocketServer } from 'ws';
import path from "path";
const dirPath = "./";
const wss = new WebSocketServer({ port: 8080 });
// Function for Adding script before </body> tag
function injection(fileName) {
let data = fs.readFileSync(fileName, 'utf-8')
data = data.replace('</body>',
`
<script >
// Code is injected for Live Reloading
const ws = new WebSocket("ws://localhost:8080");
ws.onopen = () => {
ws.send("Hello server");
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data)
if (data.message === "reload") {
if (data.type == "js") {
window.location.reload();
}
else if(data.type == "html"){
let current = location.pathname.split("/").pop();
if (!current || current === "") current = "home.html";
if (!current.includes(".")) current += ".html";
if (current === data.fileName) {
window.location.reload();
}
}
else if (data.type == "css") {
let links = document.querySelectorAll('link[rel="stylesheet"]')
Array.from(links).forEach((link) => {
if (link.href.includes(data.fileName)){
const url = new URL(link.href)
url.searchParams.set("v", Date.now())
link.href = url.toString()
}
});
}
}
};
</script>
</body> `
)
return data;
}
// Websocket Server Created
const clients = new Set()
wss.on("connection", (socket) => {
clients.add(socket);
socket.on("close", () => clients.delete(socket));
console.log("Client connected");
});
// For every client connection and detecting file changes
fs.watch("./", (eventType, filename) => {
if (!filename || eventType !== "change") return;
else if (![".html", ".css", ".js"].includes(path.extname(filename))) return;
for (const socket of clients) {
const ext = path.extname(filename)
socket.send(JSON.stringify({
type: ext === ".css" ? "css" :
ext === ".js" ? "js" : "html",
message: "reload",
fileName: filename
}));
}
});
// Server Created
const server = http.createServer((req, res) => {
if (req.url === "/" && req.method === "GET") {
res.end(injection("home.html"))
}
else if (req.method == "GET") {
const urlObj = new URL(req.url, `http://${req.headers.host}`)
// converting path name to file and storing in urlobj.filename like /style.css to style.css
urlObj.fileName = (urlObj.pathname).replace("/", "")
// if no extension → try .html
if (!path.extname(urlObj.fileName)) {
urlObj.fileName += ".html"
}
if (fs.existsSync(urlObj.fileName)) {
if (path.extname(urlObj.fileName) === ".html") {
res.end(injection(urlObj.fileName))
}
else if (path.extname(urlObj.fileName) === ".css") {
res.end(fs.readFileSync(urlObj.fileName, 'utf-8'))
}
else if (path.extname(urlObj.fileName) === ".js") {
res.end(fs.readFileSync(urlObj.fileName, 'utf-8'))
}
} else {
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 File not Found</h1>");
}
}
})
server.listen(3000)