Last active
July 1, 2022 08:10
-
-
Save MarkTiedemann/1c43c42792825d2a86f88bbd52f55a5a to your computer and use it in GitHub Desktop.
Poor Man's Live-Reload Client And Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<script> | |
var source = new EventSource('/') | |
source.onmessage = () => { | |
source.close() | |
location.reload() | |
} | |
</script> | |
</head> | |
<body> | |
<h1>Hello World!</h1> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs') | |
var http = require('http') | |
var watcher = fs.watch('index.html') | |
http | |
.createServer((req, res) => { | |
if (req.headers.accept === 'text/event-stream') { | |
res.writeHead(200, { 'content-type': 'text/event-stream' }) | |
watcher.once('change', () => res.write('data:\n\n')) | |
} else { | |
res.writeHead(200, { 'content-type': 'text/html' }) | |
fs.createReadStream('index.html').pipe(res) | |
} | |
}) | |
.listen(80) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment