Skip to content

Instantly share code, notes, and snippets.

@xslim
Created January 18, 2016 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xslim/881f6f7bc21b250fcc29 to your computer and use it in GitHub Desktop.
Save xslim/881f6f7bc21b250fcc29 to your computer and use it in GitHub Desktop.
Node.JS Event emitter to HTML5
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<input type="button" id="stopButton" value="Stop Listening"/>
<hr/>
<div id="content"></div>
<script>
var source = new EventSource('/talk');
source.addEventListener('open', function(e) {
document.getElementById('content').innerHTML += 'Connections to the server established..<br/>';
}, false);
source.onmessage = function(e) {
document.getElementById('content').innerHTML += e.data + '<br/>';
};
document.getElementById('stopButton').onclick=function(){
document.getElementById('content').innerHTML += 'Listening to server events stopped..<br/>';
source.close();
}
</script>
</body>
</html>
var http = require('http');
var fs = require('fs');
var sendInterval = 5000;
function sendServerSendEvent(req, res) {
res.writeHead(200, {
'Content-Type' : 'text/event-stream',
'Cache-Control' : 'no-cache',
'Connection' : 'keep-alive'
});
var sseId = (new Date()).toLocaleTimeString();
setInterval(function() {
writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
}, sendInterval);
writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
}
function writeServerSendEvent(res, sseId, data) {
res.write('id: ' + sseId + '\n');
res.write("data: new server event " + data + '\n\n');
}
http.createServer(function(req, res) {
if (req.headers.accept && req.headers.accept == 'text/event-stream') {
if (req.url == '/talk') {
sendServerSendEvent(req, res);
} else {
res.writeHead(404);
res.end();
}
} else {
res.writeHead(200, {
'Content-Type' : 'text/html'
});
res.write(fs.readFileSync(__dirname + '/index.html'));
res.end();
}
}).listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment