WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Intermediate · question 39 of 100

How do you create custom events using the ’EventEmitter’ class in Node.js?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

In Node.js, you can create custom events using the ‘EventEmitter‘ class which is a part of the ‘events‘ module. The ‘EventEmitter‘ class provides a way for you to create named events and associate event handlers with them. Here’s a step-by-step guide on how to create custom events using the ‘EventEmitter‘ class:

1. Import the ‘events‘ module:

const events = require('events');

2. Create a new instance of the ‘EventEmitter‘ class:

const eventEmitter = new events.EventEmitter();

3. Define custom event(s) using the ‘on()‘ method or the ‘addListener()‘ method:

eventEmitter.on('myEvent', (message) => {
  console.log(`Received: ${message}`);
});

4. Emit the custom event(s) using the ‘emit()‘ method:

eventEmitter.emit('myEvent', 'Hello, EventEmitter!');

Here’s a complete example:

// Import the 'events' module
const events = require('events');

// Create a new instance of the 'EventEmitter' class
const eventEmitter = new events.EventEmitter();

// Define a custom event called 'myEvent' and its associated event handler
eventEmitter.on('myEvent', (message) => {
  console.log(`Received: ${message}`);
});

// Trigger the custom event 'myEvent' with a custom message
eventEmitter.emit('myEvent', 'Hello, EventEmitter!');

When you run this code, you’ll see the following output:

Received: Hello, EventEmitter!

You can also define multiple event handlers for the same event by using the ‘on()‘ method multiple times:

eventEmitter.on('myEvent', (message) => {
  console.log(`Handler 1: ${message}`);
});

eventEmitter.on('myEvent', (message) => {
  console.log(`Handler 2: ${message}`);
});

Now, when you emit the ‘myEvent‘, both handlers will be executed:

Handler 1: Hello, EventEmitter!
Handler 2: Hello, EventEmitter!

Feel free to ask if you need more clarification or additional examples!

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics