a blog for those who code

Friday 19 September 2014

Create Custom Events in Nodejs

In this post we will show you how to create custom events in Nodejs. We can create an event which will execute after defined period has expired.

So suppose we are doing a specific task and wanted to know that the operation is passed or failed, we can create our own custom event which will tell us the outcome of that event.

At first we have to add events module in our application, like
var events = require('events');

After that we need to create a new instance of events.EventEmitter class. If EventEmitter instance experiences an error, it will emit an 'error' event. EventEmitters will emit 'newListener' when new listeners are added and 'removeListener' when a listener is removed.

Code:

var events = require('events');
var emitter = new events.EventEmitter();

function taskStatus(status) {

  if (status === 'done') {
     emitter.emit('done');
  } else if (status === 'doing') {
     emitter.emit('doing');
  }
}
emitter.on('done', function() {
  console.log('The task given is done!');
});
emitter.on('doing', function() {
  console.log('Doing the given task!');
});

setTimeout(taskStatus, 200, 'done');

setTimeout(taskStatus, 500, 'doing');

You will get below output when you run the above code.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment