Created
February 23, 2012 17:54
-
-
Save jedp/1894029 to your computer and use it in GitHub Desktop.
example node.js event emitter
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 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