Consider this Node.js custom event emitter class. What will be printed when the code runs?
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter { constructor() { super(); this.on('ping', () => { console.log('pong'); }); } } const emitter = new MyEmitter(); emitter.emit('ping');
Think about what happens when the 'ping' event is emitted and how the listener responds.
The 'ping' event triggers the listener which logs 'pong' to the console.
Given a custom event emitter instance, which code snippet correctly adds a listener for the 'data' event?
import { EventEmitter } from 'node:events'; const emitter = new EventEmitter();
Remember the standard method to add event listeners in Node.js EventEmitter.
The correct method is on with a callback function. Option A uses this correctly.
Examine the code below. Why does it throw an error when emitting the 'start' event?
import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter { constructor() { super(); } } const emitter = new MyEmitter(); emitter.emit('start');
Think about what happens when an event is emitted but no listeners are attached.
Emitting an event with no listeners returns false but does not throw an error.
What is the value of count after the code runs?
import { EventEmitter } from 'node:events'; class Counter extends EventEmitter { constructor() { super(); this.count = 0; this.on('increment', () => { this.count += 1; }); } } const counter = new Counter(); counter.emit('increment'); counter.emit('increment'); counter.emit('increment'); const count = counter.count;
Each 'increment' event increases count by 1. How many times is it emitted?
The 'increment' event is emitted 3 times, so count increases from 0 to 3.
Why do developers use custom event emitter classes in Node.js applications?
Think about how events help different parts of an app work together without tight connections.
Custom event emitters let different parts of an app communicate by sending and listening for events, reducing direct dependencies.