const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.emit('error', new Error('Something went wrong'));
In Node.js, if an 'error' event is emitted and there is no listener for it, the process throws the error and crashes. This is to avoid silent failures.
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('error', (err) => { console.log('Caught error:', err.message); }); emitter.emit('error', new Error('Oops!'));
The listener catches the error event and logs the message property of the error object, which is 'Oops!'.
Both on and addListener are valid methods to attach listeners. Option A uses addListener correctly with an arrow function. Option B is also valid syntax. Options C and D use invalid method names.
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.emit('error', new Error('Fail')); emitter.on('error', (err) => { console.log('Error caught:', err.message); });
Events in Node.js are synchronous. If an event is emitted before a listener is attached, that listener will not catch the event.
Node.js expects every EventEmitter that can emit 'error' events to have an 'error' listener attached. This prevents the process from crashing due to unhandled errors. Using try-catch around emit calls is ineffective because emit is synchronous but listeners run asynchronously. Global handlers like 'uncaughtException' are last-resort and not recommended for normal error handling.