Last active
August 29, 2015 14:08
-
-
Save thibauts/409a73557d9e19b85d94 to your computer and use it in GitHub Desktop.
Simple SSE middleware with implicit routing
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 app = express(); | |
var sse = new SSE(); | |
app.get('/foo', function() { | |
sse.emit('sse', { message: 'hello, sse !' }); | |
}); | |
app.use('/sse', sse.forward('sse')); // The param to forward is the name of the dispatched event |
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 EventEmitter = require('events').EventEmitter; | |
var util = require('util'); | |
function SSE() { | |
EventEmitter.call(this); | |
} | |
util.inherits(SSE, EventEmitter); | |
SSE.prototype.forward = function(eventName) { | |
var self = this; | |
return function(req, res, next) { | |
console.log('sse:open/' + eventName); | |
res.header('Content-Type', 'text/event-stream'); | |
res.header('Cache-Control', 'no-cache'); | |
res.header('Connection', 'keep-alive'); | |
var id = 0; | |
self.on(eventName, onevent); | |
function onevent(data) { | |
console.log(eventName, data); | |
res.write('id: ' + id + '\n'); | |
res.write('data: ' + JSON.stringify(data) + '\n\n'); | |
id++; | |
} | |
req.socket.once('close', function() { | |
self.removeListener(eventName, onevent); | |
console.log('sse:close/' + eventName); | |
}); | |
}; | |
} | |
module.exports = SSE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment