Events & EventEmitter
Node.js is built around an event-driven architecture. This means that certain objects (called “emitters”) emit named events that cause Function objects (“listeners”) to be called. For example, anet.Server object emits an event each time a peer connects to it; an fs.ReadStream emits an event when the file is opened; a stream emits an event whenever data is available to be read.
All objects that emit events are instances of the EventEmitter class.
The events Module
To use events, we need the events module.
Basic Usage
Registering a Listener
Use.on() to register a listener function for a specific event.
Emitting an Event
Use.emit() to trigger the event.
Passing Arguments
You can pass arguments to the event listener.Extending EventEmitter
In real-world applications, you usually extend theEventEmitter class to create your own modules that emit events.
Let’s create a Logger class that emits a ‘message’ event whenever a message is logged.
logger.js
Handling Errors
When an error occurs within anEventEmitter instance, the typical action is for an ‘error’ event to be emitted. If an EventEmitter does not have at least one listener registered for the ‘error’ event, and an ‘error’ event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.
Advanced Event Patterns
One-Time Listeners
Use.once() for listeners that should only fire once.
Removing Listeners
Listener Count and Names
Prepending Listeners
Listeners are normally added to the end of the queue. Use.prependListener() to add to the beginning.
Building a Custom Event-Driven System
Let’s build a practical example: a task queue system.Async Iterator Support
Node.js 12+ supports async iterators with events:Best Practices
Summary
- EventEmitter is the foundation of Node.js async patterns
- Use
.on()to register listeners,.emit()to trigger events - Always handle ‘error’ events to prevent crashes
- Use
.once()for one-time listeners - Extend EventEmitter to create event-driven classes
- Clean up listeners with
.off()or.removeListener()to prevent memory leaks
Summary
- Event-Driven Architecture is core to Node.js.
- The EventEmitter class is used to bind events and listeners.
- Use
.on()to listen for events. - Use
.emit()to trigger events. - You can extend
EventEmitterto build custom classes that emit events. - Always handle the
'error'event to prevent crashes.