Costa Costa - 1 year ago 83
Node.js Question

Custom Events in Node.js with Express framework

So, I'd like to know how to create custom events in node.js, and I'm hitting a wall. I'm pretty sure I'm misunderstanding something about how express works and how node.js events work. That's the app.

When a user creates a new "activity" (something that will happen many times) they send a POST request. Then within my route, if that POST succeeds I'd like to emit an event, that tells to create a new namespace for that activity.

In my route file:

var eventEmitter = require('events').EventEmitter;
// Tell about the new space.
eventEmitter.emit('new activity', {activityId:});


// When someone creates a new activity
eventEmitter.on('new activity', function (data) { // this gives and error
var newActivity = '/activity?' + data.activityId;
io.of(newActivity).on('connection', function (socket) {

// code for an activity


So the error I get is CANNOT CALL METHOD ON OF UNDEFINED and it refers to what would be line 2 in the above. I think I'm messing up my requires, maybe...or I'm not quite understanding how events work.

Any help, even a reference to good reading on Node.js events would rock!


Answer Source

You should treat EventEmitter as a class you can inherit from. Try this:

function MyEmitter () {;

util.inherits(MyEmitter, events.EventEmitter);

Now you can use your class to listen and emit events:

var e = new MyEmitter;
e.on("test", function (m) { console.log(m); });
e.emit("test", "Hello World!");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download