Skip to content

Instantly share code, notes, and snippets.

@jedp
Created February 23, 2012 17:54
Show Gist options
  • Save jedp/1894029 to your computer and use it in GitHub Desktop.
Save jedp/1894029 to your computer and use it in GitHub Desktop.
example node.js event emitter
var util = require('util');
var events = require('events');
var redis = require('redis');
var RedisQueueConsumer = function (port, host) {
events.EventEmitter.call(this);
this.port = port || 6379;
this.host = host || '127.0.0.1';
};
util.inherits(RedisQueueConsumer, events.EventEmitter);
RedisQueueConsumer.prototype.listen = function (queue) {
var r = redis.createClient(this.port, this.host);
var self = this;
function _listen() {
r.blpop(queue, 0, function(err, item) {
if (!err && item) {
self.emit('item', item);
} else {
self.emit('error', err);
}
_listen();
});
}
return _listen();
}
module.exports = RedisQueueConsumer;
if (! module.parent) {
q = new RedisQueueConsumer();
q.on('item', console.log);
q.listen('glug');
q.listen('green');
q.listen('pie');
console.log('listening to glug, green, and pie');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment