DevAcademy
LearnNode.jsEvents & EventEmitter
IntermediateNode.js

Events & EventEmitter

The pattern behind much of Node.js's core API: emitting and listening for named events.

Reading Time

12 min

Lesson

Lesson 10 of 34

The EventEmitter Pattern

Many Node.js core objects (HTTP servers, streams, child processes) are EventEmitters — they emit named events that other code can subscribe to. It is the foundation of Node.js's event-driven design.

A Basic EventEmitter

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Core EventEmitter Methods

MethodPurpose
on(event, listener)Subscribe to an event, every time it fires
once(event, listener)Subscribe to an event, but only for the first occurrence
emit(event, ...args)Fire an event, running all subscribed listeners synchronously
off(event, listener)Unsubscribe a specific listener

Building a Custom EventEmitter

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Listeners Run Synchronously

emit() calls every subscribed listener synchronously, in the order they were registered, before emit() itself returns — it does not wait for asynchronous work inside a listener to finish.

Best Practice

Always add an error listener (emitter.on('error', ...)) to any EventEmitter you expect might emit one — an unhandled 'error' event on an EventEmitter throws and can crash the process.

Interview Questions

Quick Quiz

1. What does emitter.once() do differently from emitter.on()?

2. Do EventEmitter listeners run synchronously or asynchronously when emit() is called?

3. What happens if an EventEmitter emits an "error" event with no listener attached?