Core Modules

Node.js Events

Node.js EventEmitter

Node.js EventEmitter handles custom events with emit and on methods.

Introduction to Node.js EventEmitter

Node.js is built on an event-driven architecture, which makes it highly efficient and suitable for building scalable network applications. At the heart of this architecture is the EventEmitter class, which allows developers to create, fire, and listen for custom events.

Creating an EventEmitter Instance

To start using the EventEmitter class, you need to require the events module and create an instance of the EventEmitter class.

Here's how you can create a new instance:

Emitting Events

Once you have an instance of EventEmitter, you can use the emit method to trigger an event. The first argument to emit is the name of the event you want to trigger, and subsequent arguments will be passed to any listeners for that event.

Here's an example:

Listening for Events

To handle an event, you need to register a listener using the on method. The first argument to on is the name of the event, and the second argument is a callback function that will be executed when the event is emitted.

Here's how you can listen for an event:

Handling Multiple Listeners

The EventEmitter allows you to register multiple listeners for a single event. All listeners will be called synchronously in the order they were registered.

Example with multiple listeners:

Removing Event Listeners

Sometimes, you might want to remove listeners from an event to prevent memory leaks or unwanted behavior. You can do this using the removeListener or removeAllListeners methods.

Here's an example of removing a specific listener:

To remove all listeners for a specific event:

Conclusion

Understanding how to work with events is crucial for Node.js developers as it enables the creation of efficient and responsive applications. The EventEmitter class is a powerful tool for managing events, allowing you to emit, listen, and handle events effectively.

With this knowledge, you're well-equipped to implement custom events in your Node.js applications.

Previous
Stream
Next
Path