Skip to content

Instantly share code, notes, and snippets.

@EmNudge
Last active May 12, 2024 19:10
Show Gist options
  • Save EmNudge/5d20e433919d5d36d78a03d41a2f3afe to your computer and use it in GitHub Desktop.
Save EmNudge/5d20e433919d5d36d78a03d41a2f3afe to your computer and use it in GitHub Desktop.
Minimal Live Reload
const listeners = new Set();
const addSubscriber = (res) => {
res.writeHead(200, {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
"Cache-Control": "no-cache",
});
listeners.add(res);
};
const triggerReload = (res) => {
for (const lRes of listeners) lRes.write("data: reload\n\n");
res.end();
};
const getReloadScript = (path) => `<script>
new EventSource("${path}").onmessage = () => location.reload();
</script>`;
require("http")
.createServer((req, res) => {
if (req.url === "/~_" && req.method === "GET") {
addSubscriber(res);
} else if (req.url === "/~_" && req.method === "POST") {
triggerReload(res);
} else if (
req.method === "GET" &&
(req.url === "/index.html" || req.url === "/")
) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(`${require("fs").readFileSync('./index.html')} ${getReloadScript("/~_")}`);
res.end();
} else {
res.writeHead(404);
res.end();
}
})
.listen(3000, () => {
console.log("Server listening on port http://localhost:3000");
});
# in one terminal
node server.js
# in another terminal
watchexec -e html,css,js 'curl -X POST http://localhost:3000/~_'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment