Skip to content

Instantly share code, notes, and snippets.

@jonasgeiler
Last active June 28, 2017 09:31
Show Gist options
  • Save jonasgeiler/21cb6835bb7d6d13e3d099ce11de9863 to your computer and use it in GitHub Desktop.
Save jonasgeiler/21cb6835bb7d6d13e3d099ce11de9863 to your computer and use it in GitHub Desktop.
Live-Updating HTML-File using Node.js
<html>
<head>
<style>
body {
color: #000;
font-family: Sans-serif, Helvetica;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<p>
This is my first Node.js-Script! Cool right?<br>
The HTML-File is automatically updating on changes!! Awesome!<br>
You can try it by editing and saving the index.html-File!
</p>
<script type="text/javascript">
var source = new EventSource("checkReload");
source.onmessage = function(event) {
console.log(event);
if(event.data == 'reload') {
window.location.reload(true);
}
};
</script>
</body>
</html>
var http = require('http');
var fs = require('fs');
var url = require('url');
var chokidar = require('chokidar');
var reload = false;
var oldsize = 1;
chokidar.watch('index.html')
.on('change', function(file, stats){
if(stats.size != oldsize && stats.size !== 0 && oldsize !== 0){
reload = true;
console.log('Change');
oldsize = stats.size;
}
});
http.createServer(function(request, response){
console.log(url.parse(request.url).pathname);
if(url.parse(request.url).pathname == '/checkReload'){
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
interval = setInterval(function() {
if(reload) {
response.write('data: reload\n\n');
console.log('Reload');
reload = false;
} else {
response.write('data: no-change\n\n');
}
}, 1000);
request.connection.addListener("close", function() {
clearInterval(interval);
}, false);
} else {
fs.readFile('index.html', function(err,data){
if(err){
response.writeHead(404, {'Content-Type': 'text/plain'});
console.error(err);
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(data.toString());
});
}
}).listen(8081);
console.log('Server running at http://localhost:8081/')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment