NodeJS - emitter.eventNames() Method


The emitter.eventNames() is used to retrieve an array of list with the events for which it has registered listeners. This method accepts no parameters. The values in the array can be a string or symbol.

This method belongs to Eventemitter class which is an inbuilt class of node:events module.

Syntax

Following is the syntax of the NodeJs emitter.eventNames() method −

emitter.eventNames()

Parameters

This method does not accepts any parameters.

Return value

The events for which the emitter has registered listeners are returned in an array list by this method.

Example 1

The following is the basic example of the NodeJs emitter.eventNames() Method

Here, we imported node:events module. Then we created a function one with a message inside it. Later by using emitter.eventNames() method, we returned an array listing the events which has registered listeners. So, the myEvent.eventNames() method will return an array list with event in it.

const EventEmitter = require('node:events');
const myEvent = new EventEmitter();

function one(){
  console('Welcome to Earth');
};

myEvent.on('event', one);

console.log(myEvent.eventNames());

Output

The above program produces the following output −

[ 'event' ]

Example 2

In this program, we created multiple listener functions one(), two(), and three(). So the myEvent.eventNames() method will return an array list with event1, event2, and event3 in it.

const EventEmitter = require('node:events');
const myEvent = new EventEmitter();

function one(){
  console('Hi');
};

function two(){
  console.log('Vanakkam');
};

function three(){
  console.log('Sari');
};

myEvent.on('event1', one);
myEvent.on('event2', two);
myEvent.on('event3', three);

console.log(myEvent.eventNames()); 

Output

The above program produces the following output −

[ 'event1', 'event2', 'event3' ]

Example 3

Here, we created Symbol(Symbol) because the eventName can be a string and symbols. Then we created a listener function fun(). So, the myEvent.eventNames() method will return an array list with Symbol(symbol) because the eventName we passed is a symbol.

const EventEmitter = require('node:events');
const myEvent = new EventEmitter();
const symb = Symbol('symbol');

function fun(){
  console('Welcome home...');
};

myEvent.on(symb, fun);

console.log(myEvent.eventNames());

Output

The above program produces the following output −

[ Symbol(symbol) ]
nodejs_events.htm
Advertisements