Show List
Node js events module
Events module provides EventEmitter class which is key to handle events and achieve the event driven architecture. EventEmitter object has two main functions
- Emit a named event
- Attach/Detach event listener to the event
Many core Node.js modules inherit the EventEmitter class. For example an http server emits event each time a user connects to it. fs emits an event when file is opened.
Here are the common methods from EventEmitter module:
- addListener(): Add the specified listener
- emit(): Call all the listeners registered with the specified name
- on(): Add the specified listener
- removeAllListeners(): Removes all listeners
- removeListener(): Removes the specified listener
Example
Here is an example to emit and listen to an event.
main.js:
var events = require('events');//create an object of EventEmittervar em = new events.EventEmitter();//Subscribe for Eventem.on('Event', function (data) {console.log('Event subscriber: ' + data);});// Raising Eventem.emit('Event', 'This is Node.js event emitter example.');
Running the code:
PS C:\Users\mail2\Downloads\node-js-events-module> node main Event subscriber: This is Node.js event emitter example.
Source Code:
https://github.com/it-code-lab/node-js-events-module
Leave a Comment