events.defaultMaxListeners


默认情况下,最多可为任何单个事件注册 10 个监听器。可以使用 emitter.setMaxListeners(n) 方法为单个 EventEmitter 实例更改此限制。要更改所有 EventEmitter 实例的默认值,可以使用 events.defaultMaxListeners 属性。如果该值不是正数,则抛出 RangeError

¥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.

设置 events.defaultMaxListeners 时要小心,因为更改会影响所有 EventEmitter 实例,包括在进行更改之前创建的实例。但是,调用 emitter.setMaxListeners(n) 仍然优先于 events.defaultMaxListeners

¥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.

这不是硬性限制。EventEmitter 实例将允许添加更多监听器,但会向 stderr 输出跟踪警告,指示已检测到 "可能的 EventEmitter 内存泄漏"。对于任何单个 EventEmitter,可以使用 emitter.getMaxListeners()emitter.setMaxListeners() 方法来暂时避免此警告:

¥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:

defaultMaxListenersAbortSignal 实例没有影响。虽然仍然可以使用 emitter.setMaxListeners(n) 为单个 AbortSignal 实例设置警告限制,但默认情况下 AbortSignal 实例不会触发警告。

¥defaultMaxListeners has no effect on AbortSignal instances. While it is still possible to use emitter.setMaxListeners(n) to set a warning limit for individual AbortSignal instances, per default AbortSignal instances will not warn.

import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
  // do stuff
  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
  // do stuff
  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});

--trace-warnings 命令行标志可用于显示此类警告的堆栈跟踪。

¥The --trace-warnings command-line flag can be used to display the stack trace for such warnings.

触发的警告可以使用 process.on('warning') 进行检查,并将具有额外的 emittertypecount 属性,分别指事件触发器实例、事件名称和附加监听器的数量。其 name 属性设置为 'MaxListenersExceededWarning'

¥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'.