-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
47 lines (36 loc) · 1.02 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
import express from "express";
import { readFile } from "fs";
import { watch } from "chokidar";
const app = express();
const port = 3000;
const shaderPath = "./shader.glsl";
app.use(express.static("public"));
app.get("/", (_req, res) => {
res.sendFile(__dirname + "/public/index.html");
});
const sendShader = (res) => {
readFile(shaderPath, "utf-8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return;
}
res.write(`data: ${JSON.stringify(data)}\n\n`);
});
};
app.get("/events", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.flushHeaders(); // flush the headers to establish SSE with client
let watcher = watch(shaderPath);
watcher.on("change", (_filePath) => {
sendShader(res);
});
sendShader(res);
req.on("close", () => {
watcher.close();
});
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});