Let's now learn about another core module - events.
In the video given above, you learnt how events are created and listened to in Node.js.
The steps that you need to follow are as follows:
1. Import the events module using the require keyword.
2. Create an object of the EventEmitter class.
3. Bind an event with its eventHandler using the on property.
4. Fire an event using the emit property.
In the next video, let's look at some code to understand these steps better.
The code that you looked at in the previous video is as follows:
const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('My event occurred!'); }); myEmitter.emit('event');
Output:
My event occurred!
Let's now learn how to write the same code in a slightly different way.
The code that you looked at in the previous video is as follows:
// Import events module const events = require('events'); // Create an object of EventEmitter class const eventEmitter = new events.EventEmitter(); // Define connectionMade event's handler const connectionHandler = () => { console.log('Connection succesful!'); // fire dataRecieved event eventEmitter.emit('dataReceived'); }; // bind connectionMade event with its event handler eventEmitter.on('connectionMade', connectionHandler); // bind dataReceived event with its event handler eventEmitter.on('dataReceived', () => { console.log('Data received succesfully!'); }); // Fire connectionMade event eventEmitter.emit('connectionMade'); // mark end of program console.log('End of program!');
Output:
Connection succesful! Data received succesfully! End of program!