Skip to content

Commit 221b03a

Browse files
DavidCai1111jasnell
authored andcommitted
events, doc: check input in defaultMaxListeners
PR-URL: #11938 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Yuta Hiroto <hello@about-hiroppy.com> Reviewed-By: Brian White <mscdex@mscdex.net>
1 parent 81ab78e commit 221b03a

File tree

3 files changed

+13
-11
lines changed

3 files changed

+13
-11
lines changed

doc/api/events.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,8 @@ By default, a maximum of `10` listeners can be registered for any single
262262
event. This limit can be changed for individual `EventEmitter` instances
263263
using the [`emitter.setMaxListeners(n)`][] method. To change the default
264264
for *all* `EventEmitter` instances, the `EventEmitter.defaultMaxListeners`
265-
property can be used.
265+
property can be used. If this value is not a positive number, a `TypeError`
266+
will be thrown.
266267

267268
Take caution when setting the `EventEmitter.defaultMaxListeners` because the
268269
change effects *all* `EventEmitter` instances, including those created before

lib/events.js

+4
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
5656
// force global console to be compiled.
5757
// see https://github.com/nodejs/node/issues/4467
5858
console;
59+
// check whether the input is a positive number (whose value is zero or
60+
// greater and not a NaN).
61+
if (typeof arg !== 'number' || arg < 0 || arg !== arg)
62+
throw new TypeError('"defaultMaxListeners" must be a positive number');
5963
defaultMaxListeners = arg;
6064
}
6165
});

test/parallel/test-event-emitter-max-listeners.js

+7-10
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,13 @@ e.on('maxListeners', common.mustCall(function() {}));
3030
// Should not corrupt the 'maxListeners' queue.
3131
e.setMaxListeners(42);
3232

33-
assert.throws(function() {
34-
e.setMaxListeners(NaN);
35-
}, /^TypeError: "n" argument must be a positive number$/);
33+
const throwsObjs = [NaN, -1, 'and even this'];
3634

37-
assert.throws(function() {
38-
e.setMaxListeners(-1);
39-
}, /^TypeError: "n" argument must be a positive number$/);
40-
41-
assert.throws(function() {
42-
e.setMaxListeners('and even this');
43-
}, /^TypeError: "n" argument must be a positive number$/);
35+
for (const obj of throwsObjs) {
36+
assert.throws(() => e.setMaxListeners(obj),
37+
/^TypeError: "n" argument must be a positive number$/);
38+
assert.throws(() => events.defaultMaxListeners = obj,
39+
/^TypeError: "defaultMaxListeners" must be a positive number$/);
40+
}
4441

4542
e.emit('maxListeners');

0 commit comments

Comments
 (0)