setMaxListeners Caps The Listener Warning

setMaxListeners without targets raises or lowers the process-wide listener cap; overflows warn on stderr instead of throwing.

JavascriptResilience

Code

javascriptsnippet
19 lines
import { EventEmitter, setMaxListeners } from 'node:events';

// Default cap is 10 listeners per event name per emitter
const plain = new EventEmitter();
console.log('default cap:', plain.getMaxListeners());

// Without targets, setMaxListeners changes the process-wide default
setMaxListeners(3);
console.log('after setMaxListeners(3):', new EventEmitter().getMaxListeners());

// Beyond the cap Node prints a MaxListenersExceededWarning to stderr
// instead of throwing — the listener still fires
let calls = 0;
const capped = new EventEmitter();
for (let i = 0; i < 4; i++) {
  capped.on('tick', () => calls++);
}
capped.emit('tick');
console.log('attached:', capped.listenerCount('tick'), '| handled:', calls);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

default cap: 10
after setMaxListeners(3): 3
attached: 4 | handled: 4

How the snippet works

for (let i = 0; i < 4; i++) is the loop that carries the per-item work. The import names the platform contact area: EventEmitter, setMaxListeners, all from node:events.

Top-level bindings plain, calls, capped hold the demo state — nothing sits inside a function scope.

Watch out for

  • No install needed: node:events comes with Node.js itself.

Applying it

The run emits 3 labeled sections — default cap:, after setMaxListeners(3):, attached: — one per step.

Statements that matter

capped.on('tick', () => calls++);

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:events` ships with Node.js itself.