NodeJS - emitter.getMaxListeners() Method


The emitter.getMaxListeners() method will help us to return the current maximum listener limit value for the eventEmitter which is set by emitter.setMaxListeners(n).

This method will do nothing more than return the maximum listener limit of the eventEmitter.

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

Syntax

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

emitter.getMaxListners()

Parameters

  • This method does not accept any parameters.

Return value

This method will return the count of listener functions listening to the event named eventName.

Example 1

Following is the basic example of the NodeJs emitter.getMaxListeners() Method.

Initially, we imported the node:events module. Then we passed a single listener function f1() with an eventName myEvent to the emitter.addListener() method. Then we called emitter.getMaxListeners() method by passing myEvent as a parameter. It returns 10 because By default, the EventEmitters will accept only 10 listeners for a particular event.

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

function f1(){
};

myEmitter.addListener('myEvent', f1);

console.log(myEmitter.getMaxListeners());

Output

The above program produces the following output −

10

Example 2

In this program we again passed a single listener function f1() with a eventName myEvent to the emitter.addListener() method. Then we called the emitter.setMaxListeners() method by modifying the default limit by 1.

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

function f1(){
};

myEmitter.setMaxListeners(1);
myEmitter.addListener('myEvent', f1);

console.log(myEmitter.getMaxListeners());

Output

The above program produces the following output −

1

Example 3

In this program, we set the listener limit as 1 to the specific event myEvent and we are adding 4 listeners to the same event named myEvent. So, the EventEmitter will throw a warning message that memory leak detected.

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

function f1(){
};
function f2(){
};
function f3(){
};
function f4(){
};

myEmitter.setMaxListeners(1);
myEmitter.addListener('myEvent', f1);
myEmitter.addListener('myEvent', f2);
myEmitter.addListener('myEvent', f3);
myEmitter.addListener('myEvent', f4);

console.log(myEmitter.getMaxListeners());

Output

The above program produces the following output −

1

(node:33292) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 myEvent listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
nodejs_events.htm
Advertisements