Created
November 16, 2015 23:19
-
-
Save jeremycx/9d34791429682066a0b2 to your computer and use it in GitHub Desktop.
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
/*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