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,
- Takes care of event being emitted by Node object
- 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,
After loading events module you need to create instance of EventEmitter. This can be done as follows,
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.
- Attach
- Emit
You can attach an event using on event handler. You can emit an event using emit event handler.
To attach an event you need to call on method. This takes two parameter.
- Name of the event
- 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.
In last step you can emit an event as follows. You need to pass event name and message(if any) to function.
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,
In further posts we will get into details of events in NodeJS. I hope you find this post useful. Thanks for reading.
Leave a Reply