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 实例将允许添加更多监听器,但会在标准错误输出中显示跟踪警告,表明已检测到“可能的 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:】

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