Skip to content

Instantly share code, notes, and snippets.

@jeremycx
Created November 16, 2015 23:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jeremycx/9d34791429682066a0b2 to your computer and use it in GitHub Desktop.
Save jeremycx/9d34791429682066a0b2 to your computer and use it in GitHub Desktop.
/*jshint globalstrict: true, node: true, trailing:true, unused:true */
'use strict';
var util = require('util');
module.exports = function SSEFeed() {
this.subscribers = [];
this.id = 0;
return this;
};
SSEFeed.prototype.send = function(res, type, data) {
res.write(util.format('id: %d\nevent: %s\ndata: %j\n\n',
this.id, type, data));
res.flush();
};
SSEFeed.protoype.subscribe = function() {
return function(req, res, next) {
this.subscribers.push(res);
req.socket.setTimeout(Infinity);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
req.on('close', function() {
this.subscribers.splice(this.subscribers.indexOf(res), 1);
});
return next();
};
};
SSEFeed.prototype.emit = function(type, data) {
this.id++;
this.subscribers.forEach(function(subscriber) {
this.send(subscriber, type, data);
}.bind(this));
};
/* Local Variables: */
/* mode:javascript */
/* comment-column:0 */
/* js-indent-level:4 */
/* End: */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment