Events in NodeJS : Write your first event

Setup Environment on Windows machine for Node.js Development: Part 1

Let us simplify “Hello World” Node.js Example and EventLoop : Part 2

Each objects in NodeJS emit an asynchronous event. That event is handled by an object EventEmitter. EventEmitter is underneath every object.

EventEmitter object,

  1. Takes care of event being emitted by Node object
  2. Handles events emitted by Node object

EventEmitter object provides asynchronous event handling to Node object.

Now let us use how we can create a simple event. To create and event you need to follow following steps to create an Event in Node

Load events module. You can load that as follows,

image

After loading events module you need to create instance of EventEmitter. This can be done as follows,

clip_image001

Now you can attach an event using on eventhandler and emit an event using emit eventhandler. There are two steps involved in creating an event.

  1. Attach
  2. Emit

You can attach an event using on event handler. You can emit an event using emit event handler.

clip_image001[6]

To attach an event you need to call on method. This takes two parameter.

  1. Name of the event
  2. Functions to be called when event will be emitted.

You can add an event as follows. As you see there are two parameters. ‘error’ is name of the event and errorFunction is function called when error function emits on myLogger.

clip_image001[8]

In last step you can emit an event as follows. You need to pass event name and message(if any) to function.

image

Putting all together you can create an object and add error event to that as follows,

 


var events = require('events');

var myEvents = events.EventEmitter;
var myLogger= new myEvents();

myLogger.on('error',errorfunction);
function errorfunction(message)
{
 console.log(message);
}

myLogger.emit('error','hey I am an Error');
myLogger.emit('error','hey I am not an error but still');

 

Expected output is as follows,

clip_image001[10]

In further posts we will get into details of events in NodeJS. I hope you find this post useful. Thanks for reading.

4 responses to “Events in NodeJS : Write your first event”

  1. […] Events in NodeJS : Write your first event (Dhananjay Kumar) […]

  2. […] Events in NodeJS : Write your first event […]

  3. copy and pasted code. didnt work.

  4. Dhananjay Kumar

    tell me more .. would love to help u

Leave a comment

Create a website or blog at WordPress.com