Events Module

Events Module

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.


1. The EventEmitter Class

To handle events, you need to use the EventEmitter class provided by the events module.

const EventEmitter = require('events');
const myEmitter = new EventEmitter();

2. Emitting and Listening

There are two primary methods you will use:

Basic Event Example

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.


Exercise

?

Which method is used to trigger an event?