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
| Method | Purpose |
|---|---|
| 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.