Skip to content

Instantly share code, notes, and snippets.

@MarkTiedemann
Last active July 1, 2022 08:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkTiedemann/1c43c42792825d2a86f88bbd52f55a5a to your computer and use it in GitHub Desktop.
Save MarkTiedemann/1c43c42792825d2a86f88bbd52f55a5a to your computer and use it in GitHub Desktop.
Poor Man's Live-Reload Client And Server
<!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>
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