Create a gist now

Instantly share code, notes, and snippets.

@steren /SSE DEMO.md
Last active Dec 16, 2015

What would you like to do?
var express = require('express');
var fs = require('fs');
var app = express();
app.use(express.urlencoded());
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
app.get('/', function(req, res) {
fs.readFile(__dirname + '/index.html', 'utf8', function(err, content){
res.send(content);
});
});
app.get('/message', function(req, res) {
console.log("received message: " + req.param('content'));
emitter.emit("getmessage", req.param('content'));
res.send(true);
});
var index = 0;
app.get('/stream', function(req, res) {
res.setHeader("Content-Type", 'text/event-stream');
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.writeHead(200);
res.write(":\n");
emitter.on("getmessage", function(data) {
res.write("data: " + JSON.stringify(data)+ "\n");
res.write("id: " + index + "\n\n");
index++;
});
});
app.listen(3000);
console.log('Listening on port 3000');
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>SSE</p>
<script>
document.body.innerHTML += "Demo";
var source = new EventSource('/stream');
source.addEventListener('message', function(e) {
console.log(e.data);
var data = JSON.parse(e.data);
document.body.innerHTML += data + '<br>';
}, false);
</script>
</body>
</html>
{
"name": "sse-demo",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": ">= 3.0"
},
"engines": {
"node": "*"
},
"author": "Steren Giannini <steren.giannini@gmail.com>",
"description": "Very simple demo for server sent events",
"repository": {
"url": ""
},
"main": "apps.js"
}

Simple example of Server Send Events By Steren Giannini for Paris JS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment