Thursday 4 October 2018

How to set the maximum listeners for specific emitter instance?

‘emitter.setMaxListeners()´ method is used to increase (or) decrease the maximum listeners limit. Calling emitter.setMaxListeners(n) takes precedence over EventEmitter.defaultMaxListeners.

HelloWorld.js
var EventEmitter = require('events').EventEmitter;

var emitter1 = new EventEmitter();
var emitter2 = new EventEmitter();

/* Set the maximum listeners to 29*/
emitter1.setMaxListeners(29);

console.log("Maximum listeners for emitter1 : %d", emitter1.getMaxListeners());
console.log("Maximum listeners for emitter2 : %d", emitter2.getMaxListeners());
console.log("Default Maximum listeners for all emitter instances : %d", EventEmitter.defaultMaxListeners);


Output
Maximum listeners for emitter1 : 29
Maximum listeners for emitter2 : 10
Default Maximum listeners for all emitter instances : 10

You can inspect the emitted warnings from a process using ‘proess.on('warning')’.

HelloWorld.js
var EventEmitter = require('events').EventEmitter;

EventEmitter.defaultMaxListeners = 3;

var emitter = new EventEmitter();

emitter.on('demo',() => {
 console.log("listener1");
});

emitter.on('demo',() => {
 console.log("listener2");
});

emitter.on('demo',() => {
 console.log("listener3");
});

emitter.on('demo',() => {
 console.log("listener4");
});

emitter.emit('demo');

process.on('warning', (warning) => {
  console.warn("Warning name : ", warning.name);    // Print the warning name
  console.warn("Warning message : ", warning.message); // Print the warning message
  console.warn("Warning stack trace : ", warning.stack);   // Print the stack trace
});


Output
listener1
listener2
listener3
listener4
(node:27464) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 4 demo listeners added. Use emitter.setMaxListeners() to increase limit
Warning name :  MaxListenersExceededWarning
Warning message :  Possible EventEmitter memory leak detected. 4 demo listeners added. Use emitter.setMaxListeners() to increase limit
Warning stack trace :  MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 4 demo listeners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:243:17)
    at EventEmitter.addListener (events.js:259:10)
    at Object.<anonymous> (C:\Users\krishna\Documents\Study\nodejs\examples\HelloWorld.js:19:9)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:266:19)


Previous                                                 Next                                                 Home

No comments:

Post a Comment