events.defaultMaxListeners
默认情况下,最多可为任何单个事件注册 10
个监听器。
可以使用 emitter.setMaxListeners(n)
方法为单个 EventEmitter
实例更改此限制。
要更改所有 EventEmitter
实例的默认值,则可以使用 events.defaultMaxListeners
属性。
如果该值不是正数,则抛出 RangeError
。
设置 events.defaultMaxListeners
时要小心,因为更改会影响所有 EventEmitter
实例,包括在进行更改之前创建的实例。
但是,调用 emitter.setMaxListeners(n)
仍然优先于 events.defaultMaxListeners
。
这不是硬性限制。
EventEmitter
实例将允许添加更多监听器,但会向标准错误输出跟踪警告,指示已检测到"可能的 EventEmitter 内存泄漏"。
对于任何单个 EventEmitter
,可以使用 emitter.getMaxListeners()
和 emitter.setMaxListeners()
方法来暂时避免此警告:
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// 做些事情
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
--trace-warnings
命令行标志可用于显示此类警告的堆栈跟踪。
触发的警告可以使用 process.on('warning')
进行检查,并将具有额外的 emitter
、type
和 count
属性,分别是指事件触发器实例、事件名称和绑定监听器的数量。
其 name
属性设置为 'MaxListenersExceededWarning'
。
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 events.defaultMaxListeners
property can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
change affects all EventEmitter
instances, including those created before
the change is made. However, calling emitter.setMaxListeners(n)
still has
precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
more listeners to be added but will output a trace warning to stderr indicating
that a "possible EventEmitter memory leak" has been detected. For any single
EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to temporarily avoid this warning:
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
The --trace-warnings
command-line flag can be used to display the
stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
have the additional emitter
, type
and count
properties, referring to
the event emitter instance, the event’s name and the number of attached
listeners, respectively.
Its name
property is set to 'MaxListenersExceededWarning'
.