How to create custom event listener in node.js (express.js)?

I just came across this question, I'd like to chip in my 2 cents, specifically responding to Luis.

In Express, if you want the 'app' instance to listen for a custom event you would do something like:

app.on('testEvent', function () {
  return console.log('responded to testEvent');
});

app.get('/test', function (req, res) {
  app.emit('testEvent');
  return res.status(200).end();
});

Then when that route is hit, you'd see the response in the console. Of course you can implement this as you wish.


You probably want to create an EventEmitter object, and call emit() on it.


You can set events like this

app.on('event:user_created', callback);

Then you can emit them

app.emit('event:user_created', data);

express.js uses EventEmitter.

Tags:

Events

Node.Js