How to Use Event Emitters in Node.js

Event emitters are objects in NodeJS that raise events by sending a message to signal that an action has taken place.


Node.js provides a built-in event engine. It includes an event emitter class that allows you to create and handle custom events through callback functions.

Learn how to emit events, listen and process event data, and handle event errors in NodeJS.


outputting events

The events engine is a core part of the Node.js server-side environment. So you don’t have to install it, but before you use the event emitter Class you must import and instantiate from the event module.

So:

const EventEmitter = require("events");


const myEmitter = new EventEmitter();

You can output events with event emitter‘s emit Method. That emit method takes a event name and any number of arguments as parameters.

As soon as you call emit method it outputs the passed event name. Then it synchronously invokes all of the event’s listeners in the order you registered them, passing the provided arguments to each. It’s finally coming back Is correct whether the event had an audience and NOT CORRECT if it had no listeners.

For example:

myEmitter.emit("TestEvent", "foo", "bar", 1, 2);

In the code block above, you passed test event as the event name, and “Foo“Bar1and 2 as arguments. When the above code block runs, it notifies all listeners that are listening to the test event Event. It calls these listeners with the given arguments.

Listen to events

You can listen to emitted events using event emitter‘s on Method. That on method takes a event name and a callback function as a parameter. If the event with the event name into which passed on method is issued, it calls its callback function. This method returns a reference to the event emitterso you can chain multiple calls together.

Read  How to put lime on your lawn and when to do it

For example:


myEmitter.on("TestEvent", () => {
console.log("TestEvent Emitted!!!");
});


myEmitter.on("TestEvent", (...args) => {
args = args.join(", ");
console.log(`Event emitted with the following arguments: ${args}`);
});

myEmitter.emit("TestEvent", "foo", "bar", 1, 2);

In the code block above if the test event event, the listeners for the event call their callback functions. The listeners respond in the order in which you registered them, which means that the “first listener’s” callback is executed before the second, and so on.

You can change this behavior with event emitter‘s prependListener Method. This method uses the same parameters as the on Method. The difference is that this method responds to the event first, regardless of when you register it.

For example:

myEmitter.on("TestEvent", () => {
console.log("TestEvent Emitted!!!");
});

myEmitter.prependListener("TestEvent", () => {
console.log("Executes first")
})

// console.log(myEmitter.listeners("TestEvent"));
myEmitter.emit("TestEvent", "foo", "bar", 1, 2);

When the above code block is executed, “Executes first” is first logged to the console, followed by “TestEvent Emitted!!!”. regardless of the order in which you registered them based on the prependListener Method.

If you have several listeners at the prependListener method, they are executed in order from last to first.

Note the arrangement of transmitter and listener. The listeners always come before the station. This arrangement is because the listeners must already be listening to the event before the emitter broadcasts it.

For context, consider the following block of code:

myEmitter.emit("TestEvent", "foo", "bar", 1, 2);

myEmitter.on("TestEvent", () => {
console.log("TestEvent Emitted!!!");
});

When you run the code block above, nothing happens because there was no listener listening to the event at the time the emitter sent out the event.

Read  How To Get A Good Interest Rate For A Personal Loan

One-time listening to events

Depending on your needs, you might only need to handle some events once in the lifecycle of your application. You can achieve this with the event emitter‘s once Method.

This method accepts the same arguments as the on method and works similarly. The only difference is that the listeners have registered with the once method listen for the event only once.

For example:

myEmitter.once("SingleEvent", () => {
console.log("Event handled once");
});

myEmitter.emit("SingleEvent"); // Event handled once
myEmitter.emit("SingleEvent"); // Ignored
myEmitter.emit("SingleEvent"); // Ignored

By running the code block, “Event Handled Once” is only logged once to the console, regardless of how many times the emitter emits the event.

At the registered listener once method respond to the event in the order in which you register them. You can change this behavior with prependOnceListener method how works prependListener. The only difference is that the listeners have registered with the once method listen for the event only once.

Handling errors with event emitters

You should take care to handle JavaScript errors appropriately, and event listeners are no exception. Unhandled errors from them will result in the Node.js process terminating and your application crashing.

To handle an error event, at least one of the event’s listeners must have an error event event name set to errors.

For example:

myEmitter.on("error", (error) => {
console.error(`Error: ${error}`);
});

Having a listener handle a potential error, as in the code block above, prevents the application from crashing when an error occurs.

Read  How to Redownload Games on the Nintendo Switch

For example:

myEmitter.emit("error", new Error("This is an error"));

Running the above code block will log “This is an error” to the console because a listener is handling error events.

Manage event listeners

That event emitter class has several methods that you can use to manipulate and manage event listeners. You can get an event’s listeners, remove them, and set the maximum number of listeners for an event.

Here is a table with event emitter Methods you can use to manipulate event listeners:

method arguments return value
ListenerCount event name Returns the number of listeners subscribed to an event
listeners event name Returns an array of listeners
Remove listeners event name Removes one or more listeners from a specified eventName.
Remove all listeners event name Removes all listeners for a specified eventName. If you don’t specify an event name, this method call removes all listeners for the EventEmitter.
setMaxListeners number Changes the default maximum number of listeners per event. Use infinity or null to indicate an unlimited number of listeners. By default, you can only subscribe to ten listeners for an event.

You can only call these methods on one event emitter Example.

For example:

myEmitter.removeListener("TestEvent");

The code block above removes a single listener for the test event Event.

The importance of event emitters

Node.js adopts the event-driven programming paradigm with its support for event emitters and listeners. Event-driven programming is one of the reasons Node.js programs are faster and less complicated than some alternatives. You can easily synchronize multiple events, resulting in improved efficiency.

Leave a Comment

Your email address will not be published. Required fields are marked *