Events lie at the heart of Node.js. In fact, events ARE the heart of Node.js. When building our own custom modules, we are able to make use of this functionality provided by Node.js for emitting our very own events. We can do this by using the EventEmitter exposed by the built-in ‘events’ module. The following code snippet demonstrates how to use the simple API of the EventEmitter.
var events = require(‘events’);
var eventEmitter = new events.EventEmitter();
eventEmitter.emit(‘someOccurence’, ‘Something happened!’);
After creating an eventEmitter object, we subscribe to an event named ‘someOccurence’ and register a function with a message argument to be called when the event is raised. Subscribing is done by executing the on() method of the eventEmitter object. Next we raise our event by simply calling the emit() method of the eventEmitter object, also passing in the value for the message argument of the event handler function.
ProsperaSoft offers Node.js development solutions. You can email at firstname.lastname@example.org to get in touch with ProsperaSoft Node.js experts and consultants.