Much of the internal architecture is built around an event-driven design. The Events module allows you to create, listen to, and trigger custom events.
If you have used JavaScript in the browser (e.g., listening for a button "click"), you already understand events. On the backend, you can listen for events like a file finishing reading, or a user connecting to a server.
To handle events, you need to use the EventEmitter class provided by the events module.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
There are two primary methods you will use:
.on(): Sets up a listener. It waits for a specific event to be triggered..emit(): Triggers the event and passes along any required data.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// 1. Set up the listener
myEmitter.on('userJoined', (username) => {
console.log('Welcome to the server, ' + username + '!');
});
// 2. Trigger the event later in the code
console.log('Server is running...');
myEmitter.emit('userJoined', 'Alice');
myEmitter.emit('userJoined', 'Bob');
In the example above, .on('userJoined') waits for the 'userJoined' event. When we call .emit('userJoined', 'Alice'), the listener activates and prints the message to the console.
Which method is used to trigger an event?