Core Modules
Node.js Events
Node.js EventEmitter
Node.js EventEmitter handles custom events with emit and on methods.
Introduction to Node.js Events
Node.js is an event-driven platform, making it suitable for building asynchronous applications. At the heart of Node.js's event architecture is the EventEmitter class, which provides a way to create, listen to, and manage custom events.
Understanding EventEmitter
The EventEmitter
class is part of the events
module in Node.js. It allows you to define your own events and bind listeners to them. This is particularly useful for creating asynchronous, non-blocking code.
To utilize EventEmitter
, you must first import the events
module and create an instance of EventEmitter
.
Emitting Events
To trigger an event, use the emit
method. This method raises the specified event, calling all the listeners attached to it. The first argument to emit
is the event name, and any subsequent arguments are passed to the event listeners.
Listening for Events
The on
method is used to register a listener for a specific event. This listener is a callback function that gets executed whenever the specified event is emitted.
Here is how you can add a listener to an event:
Example: Custom Event Handling
Let's put it all together in an example where we create a custom event and handle it using the EventEmitter
class. In this example, we will emit a 'greet' event with a name and age, and listen for it to print a greeting.
Managing Multiple Event Listeners
Node.js allows you to add multiple listeners to a single event. These listeners will be executed in the order they were added. You can manage these listeners using methods like once
for one-time listeners and removeListener
to remove specific listeners.