Skip to content

Commit

Permalink
events, doc: check input in defaultMaxListeners
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
DavidCai1111 authored and jasnell committed Mar 22, 2017
1 parent 81ab78e commit 221b03a
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 11 deletions.
3 changes: 2 additions & 1 deletion doc/api/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,8 @@ By default, a maximum of `10` listeners can be registered for any single
event. This limit can be changed for individual `EventEmitter` instances
using the [`emitter.setMaxListeners(n)`][] method. To change the default
for *all* `EventEmitter` instances, the `EventEmitter.defaultMaxListeners`
property can be used.
property can be used. If this value is not a positive number, a `TypeError`
will be thrown.

Take caution when setting the `EventEmitter.defaultMaxListeners` because the
change effects *all* `EventEmitter` instances, including those created before
Expand Down
4 changes: 4 additions & 0 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
// force global console to be compiled.
// see https://github.com/nodejs/node/issues/4467
console;
// check whether the input is a positive number (whose value is zero or
// greater and not a NaN).
if (typeof arg !== 'number' || arg < 0 || arg !== arg)
throw new TypeError('"defaultMaxListeners" must be a positive number');
defaultMaxListeners = arg;
}
});
Expand Down
17 changes: 7 additions & 10 deletions test/parallel/test-event-emitter-max-listeners.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,13 @@ e.on('maxListeners', common.mustCall(function() {}));
// Should not corrupt the 'maxListeners' queue.
e.setMaxListeners(42);

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

assert.throws(function() {
e.setMaxListeners(-1);
}, /^TypeError: "n" argument must be a positive number$/);

assert.throws(function() {
e.setMaxListeners('and even this');
}, /^TypeError: "n" argument must be a positive number$/);
for (const obj of throwsObjs) {
assert.throws(() => e.setMaxListeners(obj),
/^TypeError: "n" argument must be a positive number$/);
assert.throws(() => events.defaultMaxListeners = obj,
/^TypeError: "defaultMaxListeners" must be a positive number$/);
}

e.emit('maxListeners');

0 comments on commit 221b03a

Please sign in to comment.