Bird
Raised Fist0
Node.jsframework~10 mins

EventEmitter class in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - EventEmitter class
Create EventEmitter instance
Register listener with on()
Emit event with emit()
Check if listeners exist
Call listeners
Listeners run their code
End
This flow shows how an EventEmitter instance is created, listeners are registered, events are emitted, and listeners are called if they exist.
Execution Sample
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', () => console.log('Hello!'));
emitter.emit('greet');
This code creates an EventEmitter, adds a listener for 'greet', then emits 'greet' causing the listener to run.
Execution Table
StepActionEventListeners RegisteredListeners CalledOutput
1Create EventEmitter instance-[]--
2Register listener with on()greet['greet' listener]--
3Emit event with emit()greet['greet' listener]YesHello!
4No more listeners to call-['greet' listener]No-
💡 All listeners for 'greet' event have been called; no more listeners to invoke.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
emitter.listeners('greet')[][][Function][Function][Function]
Key Moments - 2 Insights
Why does the listener function run only after emit() is called?
Listeners are stored when registered with on(), but they only run when emit() triggers the event, as shown in execution_table step 3.
What happens if emit() is called for an event with no listeners?
No listeners are called and nothing happens, as shown in the 'No' branch in concept_flow and no output in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 3?
AError
BNo output
CHello!
Dundefined
💡 Hint
Check the Output column at step 3 in execution_table.
At which step are listeners registered for the 'greet' event?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the Action and Listeners Registered columns in execution_table.
If we emit an event with no listeners, what happens according to the concept_flow?
AAn error is thrown
BNothing happens
CListeners run anyway
DA default listener runs
💡 Hint
Refer to the 'No' branch after 'Check if listeners exist' in concept_flow.
Concept Snapshot
EventEmitter class lets you create objects that can emit named events.
Use on(event, listener) to register functions to run when that event happens.
Use emit(event) to trigger all listeners for that event.
If no listeners exist, emit does nothing.
Listeners run in order they were added.
Full Transcript
The EventEmitter class in Node.js allows you to create an object that can emit events and have functions listen to those events. First, you create an EventEmitter instance. Then, you register listeners for specific event names using the on() method. When you call emit() with an event name, all listeners registered for that event run in the order they were added. If no listeners exist for an event, emitting it does nothing. This flow helps organize code to react to events asynchronously.

Practice

(1/5)
1. What is the main purpose of the EventEmitter class in Node.js?
easy
A. To manage file system operations
B. To handle HTTP requests and responses
C. To allow parts of a program to send and listen for events
D. To create and manage database connections

Solution

  1. Step 1: Understand the role of EventEmitter

    The EventEmitter class is designed to let different parts of a program communicate by sending and listening for events.
  2. Step 2: Compare with other options

    Options B, C, and D relate to other Node.js modules like HTTP, FS, and database modules, not EventEmitter.
  3. Final Answer:

    To allow parts of a program to send and listen for events -> Option C
  4. Quick Check:

    EventEmitter = event communication [OK]
Hint: EventEmitter is about events, not HTTP or files [OK]
Common Mistakes:
  • Confusing EventEmitter with HTTP or file system modules
  • Thinking EventEmitter manages databases
  • Assuming EventEmitter runs code synchronously
2. Which of the following is the correct way to listen for an event named data using an EventEmitter instance called emitter?
easy
A. emitter.on('data', callback)
B. emitter.listen('data', callback)
C. emitter.emit('data', callback)
D. emitter.addEvent('data', callback)

Solution

  1. Step 1: Identify the method to listen for events

    The on method is used to register a callback to listen for a named event.
  2. Step 2: Check other methods

    emit sends events, not listens. listen and addEvent are not valid EventEmitter methods.
  3. Final Answer:

    emitter.on('data', callback) -> Option A
  4. Quick Check:

    Listen with on() = emitter.on('data', callback) [OK]
Hint: Use on() to listen, emit() to send events [OK]
Common Mistakes:
  • Using emit() to listen instead of send
  • Using non-existent methods like listen()
  • Confusing method names for event handling
3. What will be the output of the following code?
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', name => {
  console.log(`Hello, ${name}!`);
});
emitter.emit('greet', 'Alice');
medium
A. greet Alice
B. No output
C. Error: greet event not found
D. Hello, Alice!

Solution

  1. Step 1: Understand event registration

    The code registers a listener for the 'greet' event that prints a greeting with the given name.
  2. Step 2: Understand event emission

    When emit('greet', 'Alice') runs, it calls the listener with 'Alice', printing "Hello, Alice!".
  3. Final Answer:

    Hello, Alice! -> Option D
  4. Quick Check:

    emit triggers on() callback [OK]
Hint: emit calls on() listeners with arguments [OK]
Common Mistakes:
  • Expecting no output if event name is wrong
  • Confusing emit with on
  • Thinking emit returns a value
4. Identify the error in this code snippet:
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.emit('start');
emitter.on('start', () => {
  console.log('Started');
});
medium
A. The event name 'start' is invalid
B. The event listener is registered after emitting the event
C. emit() requires a callback function as second argument
D. The EventEmitter class is not imported correctly

Solution

  1. Step 1: Check event listener registration timing

    The listener for 'start' is added after the event is emitted, so it misses the event.
  2. Step 2: Verify other options

    EventEmitter is imported correctly, emit() does not require a callback, and 'start' is a valid event name.
  3. Final Answer:

    The event listener is registered after emitting the event -> Option B
  4. Quick Check:

    Listeners must be added before emit() [OK]
Hint: Add listeners before emitting events [OK]
Common Mistakes:
  • Emitting before listener registration
  • Thinking emit needs a callback argument
  • Assuming event names have restrictions
5. You want to create an EventEmitter that counts how many times an event ping is emitted and logs the count each time. Which code correctly implements this?
hard
A. const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.on('ping', () => { count++; console.log(`Ping count: ${count}`); }); emitter.emit('ping'); emitter.emit('ping');
B. const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.emit('ping', () => { count++; console.log(`Ping count: ${count}`); });
C. const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.on('ping', count++); emitter.emit('ping');
D. const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.on('ping', () => count++); emitter.emit('ping'); console.log(`Ping count: ${count}`);

Solution

  1. Step 1: Understand event counting logic

    We need to increase count and log it inside the event listener each time 'ping' is emitted.
  2. Step 2: Analyze each option

    const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.on('ping', () => { count++; console.log(`Ping count: ${count}`); }); emitter.emit('ping'); emitter.emit('ping'); correctly registers a listener that increments and logs count on each 'ping'. const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.emit('ping', () => { count++; console.log(`Ping count: ${count}`); }); wrongly uses emit with a callback. const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.on('ping', count++); emitter.emit('ping'); passes count++ directly, which is incorrect. const EventEmitter = require('events'); const emitter = new EventEmitter(); let count = 0; emitter.on('ping', () => count++); emitter.emit('ping'); console.log(`Ping count: ${count}`); increments count but logs outside the event, so only logs once.
  3. Final Answer:

    Option A code correctly counts and logs on each ping event -> Option A
  4. Quick Check:

    Increment and log inside on() callback [OK]
Hint: Increment count inside on() callback, not outside [OK]
Common Mistakes:
  • Passing callback to emit() instead of on()
  • Incrementing count outside event listener
  • Using count++ directly as listener instead of function