Node.js v22.2.0 文档


事件#

¥Events

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: lib/events.js

许多 Node.js 核心 API 都是围绕惯用的异步事件驱动架构构建的,在该架构中,某些类型的对象(称为 "触发器")触发命名事件,导致调用 Function 对象("监听器")。

¥Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause Function objects ("listeners") to be called.

例如:每当对等连接到 net.Server 对象时,它都会触发一个事件;当文件被打开时,fs.ReadStream 触发一个事件;只要数据可供读取, 就会触发一个事件。

¥For instance: a net.Server object emits an event each time a peer connects to it; a fs.ReadStream emits an event when the file is opened; a stream emits an event whenever data is available to be read.

所有触发事件的对象都是 EventEmitter 类的实例。这些对象暴露了 eventEmitter.on() 函数,允许将一个或多个函数绑定到对象触发的命名事件。通常,事件名称是驼峰式字符串,但也可以使用任何有效的 JavaScript 属性键。

¥All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.

EventEmitter 对象触发事件时,将同步调用附加到该特定事件的所有函数。调用的监听器返回的任何值都将被忽略和丢弃。

¥When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and discarded.

以下示例展示了使用单个监听器的简单的 EventEmitter 实例。eventEmitter.on() 方法用于注册监听器,eventEmitter.emit() 方法用于触发事件。

¥The following example shows a simple EventEmitter instance with a single listener. The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event.

import { EventEmitter } from 'node:events';

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');const EventEmitter = require('node:events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');

将参数和 this 传递给监听器#

¥Passing arguments and this to listeners

eventEmitter.emit() 方法允许将任意一组参数传给监听器函数。记住,当调用普通的监听器函数时,标准的 this 关键字会被有意地设置为引用监听器绑定到的 EventEmitter 实例。

¥The eventEmitter.emit() method allows an arbitrary set of arguments to be passed to the listener functions. Keep in mind that when an ordinary listener function is called, the standard this keyword is intentionally set to reference the EventEmitter instance to which the listener is attached.

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
  console.log(a, b, this, this === myEmitter);
  // Prints:
  //   a b MyEmitter {
  //     _events: [Object: null prototype] { event: [Function (anonymous)] },
  //     _eventsCount: 1,
  //     _maxListeners: undefined,
  //     [Symbol(shapeMode)]: false,
  //     [Symbol(kCapture)]: false
  //   } true
});
myEmitter.emit('event', 'a', 'b');const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
  console.log(a, b, this, this === myEmitter);
  // Prints:
  //   a b MyEmitter {
  //     _events: [Object: null prototype] { event: [Function (anonymous)] },
  //     _eventsCount: 1,
  //     _maxListeners: undefined,
  //     [Symbol(shapeMode)]: false,
  //     [Symbol(kCapture)]: false
  //   } true
});
myEmitter.emit('event', 'a', 'b');

可以使用 ES6 箭头函数作为监听器,但是,这样做时,this 关键字将不再引用 EventEmitter 实例:

¥It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the this keyword will no longer reference the EventEmitter instance:

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  console.log(a, b, this);
  // Prints: a b undefined
});
myEmitter.emit('event', 'a', 'b');const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  console.log(a, b, this);
  // Prints: a b {}
});
myEmitter.emit('event', 'a', 'b');

异步与同步#

¥Asynchronous vs. synchronous

EventEmitter 按照注册的顺序同步地调用所有监听器。这确保了事件的正确排序,并有助于避免竞争条件和逻辑错误。在适当的时候,监听器函数可以使用 setImmediate()process.nextTick() 方法切换到异步的操作模式:

¥The EventEmitter calls all listeners synchronously in the order in which they were registered. This ensures the proper sequencing of events and helps avoid race conditions and logic errors. When appropriate, listener functions can switch to an asynchronous mode of operation using the setImmediate() or process.nextTick() methods:

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('this happens asynchronously');
  });
});
myEmitter.emit('event', 'a', 'b');const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('this happens asynchronously');
  });
});
myEmitter.emit('event', 'a', 'b');

只处理一次事件#

¥Handling events only once

当使用 eventEmitter.on() 方法注册监听器时,每次触发命名事件时都会调用该监听器。

¥When a listener is registered using the eventEmitter.on() method, that listener is invoked every time the named event is emitted.

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
let m = 0;
myEmitter.on('event', () => {
  console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Prints: 2const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
let m = 0;
myEmitter.on('event', () => {
  console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Prints: 2

使用 eventEmitter.once() 方法,可以注册一个监听器,该监听器最多为特定事件调用一次。事件触发后,监听器将被取消注册,然后被调用。

¥Using the eventEmitter.once() method, it is possible to register a listener that is called at most once for a particular event. Once the event is emitted, the listener is unregistered and then called.

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
let m = 0;
myEmitter.once('event', () => {
  console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Ignoredconst EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
let m = 0;
myEmitter.once('event', () => {
  console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Ignored

错误事件#

¥Error events

EventEmitter 实例中发生错误时,典型的操作是触发 'error' 事件。这些在 Node.js 中被视为特殊情况。

¥When an error occurs within an EventEmitter instance, the typical action is for an 'error' event to be emitted. These are treated as special cases within Node.js.

如果 EventEmitter 没有为 'error' 事件注册至少一个监听器,并且触发 'error' 事件,则会抛出错误,打印堆栈跟踪,然后 Node.js 进程退出。

¥If an EventEmitter does not have at least one listener registered for the 'error' event, and an 'error' event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.jsconst EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js

为了防止 Node.js 进程崩溃,可以使用 domain 模块。(但请注意,不推荐使用 node:domain 模块。)

¥To guard against crashing the Node.js process the domain module can be used. (Note, however, that the node:domain module is deprecated.)

作为最佳实践,应始终为 'error' 事件添加监听器。

¥As a best practice, listeners should always be added for the 'error' events.

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
  console.error('whoops! there was an error');
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an errorconst EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
  console.error('whoops! there was an error');
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an error

通过使用符号 events.errorMonitor 安装监听器,可以在不消费触发的错误的情况下监视 'error' 事件。

¥It is possible to monitor 'error' events without consuming the emitted error by installing a listener using the symbol events.errorMonitor.

import { EventEmitter, errorMonitor } from 'node:events';

const myEmitter = new EventEmitter();
myEmitter.on(errorMonitor, (err) => {
  MyMonitoringTool.log(err);
});
myEmitter.emit('error', new Error('whoops!'));
// Still throws and crashes Node.jsconst { EventEmitter, errorMonitor } = require('node:events');

const myEmitter = new EventEmitter();
myEmitter.on(errorMonitor, (err) => {
  MyMonitoringTool.log(err);
});
myEmitter.emit('error', new Error('whoops!'));
// Still throws and crashes Node.js

捕获对 promise 的拒绝#

¥Capture rejections of promises

async 函数与事件句柄一起使用是有问题的,因为它会在抛出异常的情况下导致未处理的拒绝:

¥Using async functions with event handlers is problematic, because it can lead to an unhandled rejection in case of a thrown exception:

import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
ee.on('something', async (value) => {
  throw new Error('kaboom');
});const EventEmitter = require('node:events');
const ee = new EventEmitter();
ee.on('something', async (value) => {
  throw new Error('kaboom');
});

EventEmitter 构造函数中的 captureRejections 选项或全局的设置可以改变这种行为,在 Promise 上安装 .then(undefined, handler) 句柄。此句柄将异常异步地路由到 Symbol.for('nodejs.rejection') 方法(如果有)或 'error' 事件句柄(如果没有)。

¥The captureRejections option in the EventEmitter constructor or the global setting change this behavior, installing a .then(undefined, handler) handler on the Promise. This handler routes the exception asynchronously to the Symbol.for('nodejs.rejection') method if there is one, or to 'error' event handler if there is none.

import { EventEmitter } from 'node:events';
const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
  throw new Error('kaboom');
});

ee1.on('error', console.log);

const ee2 = new EventEmitter({ captureRejections: true });
ee2.on('something', async (value) => {
  throw new Error('kaboom');
});

ee2[Symbol.for('nodejs.rejection')] = console.log;const EventEmitter = require('node:events');
const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
  throw new Error('kaboom');
});

ee1.on('error', console.log);

const ee2 = new EventEmitter({ captureRejections: true });
ee2.on('something', async (value) => {
  throw new Error('kaboom');
});

ee2[Symbol.for('nodejs.rejection')] = console.log;

设置 events.captureRejections = true 将更改 EventEmitter 的所有新实例的默认值。

¥Setting events.captureRejections = true will change the default for all new instances of EventEmitter.

import { EventEmitter } from 'node:events';

EventEmitter.captureRejections = true;
const ee1 = new EventEmitter();
ee1.on('something', async (value) => {
  throw new Error('kaboom');
});

ee1.on('error', console.log);const events = require('node:events');
events.captureRejections = true;
const ee1 = new events.EventEmitter();
ee1.on('something', async (value) => {
  throw new Error('kaboom');
});

ee1.on('error', console.log);

captureRejections 行为生成的 'error' 事件没有捕获处理程序以避免无限错误循环:建议不要使用 async 函数作为 'error' 事件处理程序。

¥The 'error' events that are generated by the captureRejections behavior do not have a catch handler to avoid infinite error loops: the recommendation is to not use async functions as 'error' event handlers.

类:EventEmitter#

¥Class: EventEmitter

EventEmitter 类由 node:events 模块定义和暴露:

¥The EventEmitter class is defined and exposed by the node:events module:

import { EventEmitter } from 'node:events';const EventEmitter = require('node:events');

所有 EventEmitter 在添加新监听器时触发事件 'newListener',在删除现有监听器时触发 'removeListener'

¥All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when existing listeners are removed.

它支持以下的选项:

¥It supports the following option:

事件:'newListener'#

¥Event: 'newListener'

在将监听器添加到其内部监听器数组之前,EventEmitter 实例将触发自己的 'newListener' 事件。

¥The EventEmitter instance will emit its own 'newListener' event before a listener is added to its internal array of listeners.

'newListener' 事件注册的监听器会传入事件名称和对正在添加的监听器的引用。

¥Listeners registered for the 'newListener' event are passed the event name and a reference to the listener being added.

在添加监听器之前触发事件的事实具有微妙但重要的副作用:在 'newListener' 回调中注册到同一 name 的任何其他监听器都将插入到正在添加的监听器之前。

¥The fact that the event is triggered before adding the listener has a subtle but important side effect: any additional listeners registered to the same name within the 'newListener' callback are inserted before the listener that is in the process of being added.

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
// Only do this once so we don't loop forever
myEmitter.once('newListener', (event, listener) => {
  if (event === 'event') {
    // Insert a new listener in front
    myEmitter.on('event', () => {
      console.log('B');
    });
  }
});
myEmitter.on('event', () => {
  console.log('A');
});
myEmitter.emit('event');
// Prints:
//   B
//   Aconst EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
// Only do this once so we don't loop forever
myEmitter.once('newListener', (event, listener) => {
  if (event === 'event') {
    // Insert a new listener in front
    myEmitter.on('event', () => {
      console.log('B');
    });
  }
});
myEmitter.on('event', () => {
  console.log('A');
});
myEmitter.emit('event');
// Prints:
//   B
//   A

事件:'removeListener'#

¥Event: 'removeListener'

'removeListener' 事件在 listener 被删除后触发。

¥The 'removeListener' event is emitted after the listener is removed.

emitter.addListener(eventName, listener)#

emitter.on(eventName, listener) 的别名。

¥Alias for emitter.on(eventName, listener).

emitter.emit(eventName[, ...args])#

按注册顺序同步地调用为名为 eventName 的事件注册的每个监听器,并将提供的参数传给每个监听器。

¥Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.

如果事件有监听器,则返回 true,否则返回 false

¥Returns true if the event had listeners, false otherwise.

import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();

// First listener
myEmitter.on('event', function firstListener() {
  console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
  console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
  const parameters = args.join(', ');
  console.log(`event with parameters ${parameters} in third listener`);
});

console.log(myEmitter.listeners('event'));

myEmitter.emit('event', 1, 2, 3, 4, 5);

// Prints:
// [
//   [Function: firstListener],
//   [Function: secondListener],
//   [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listenerconst EventEmitter = require('node:events');
const myEmitter = new EventEmitter();

// First listener
myEmitter.on('event', function firstListener() {
  console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
  console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
  const parameters = args.join(', ');
  console.log(`event with parameters ${parameters} in third listener`);
});

console.log(myEmitter.listeners('event'));

myEmitter.emit('event', 1, 2, 3, 4, 5);

// Prints:
// [
//   [Function: firstListener],
//   [Function: secondListener],
//   [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener

emitter.eventNames()#

返回列出触发器已为其注册监听器的事件的数组。数组中的值是字符串或 Symbol

¥Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

import { EventEmitter } from 'node:events';

const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

const sym = Symbol('symbol');
myEE.on(sym, () => {});

console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]const EventEmitter = require('node:events');

const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

const sym = Symbol('symbol');
myEE.on(sym, () => {});

console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]

emitter.getMaxListeners()#

返回 EventEmitter 的当前最大监听器数的值,该值由 emitter.setMaxListeners(n) 设置或默认为 events.defaultMaxListeners

¥Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.

emitter.listenerCount(eventName[, listener])#

返回监听名为 eventName 的事件的监听器数量。如果提供了 listener,它将返回在事件的监听器列表中找到监听器的次数。

¥Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

emitter.listeners(eventName)#

返回名为 eventName 的事件的监听器数组的副本。

¥Returns a copy of the array of listeners for the event named eventName.

server.on('connection', (stream) => {
  console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ] 

emitter.off(eventName, listener)#

emitter.removeListener() 的别名。

¥Alias for emitter.removeListener().

emitter.on(eventName, listener)#

listener 函数添加到名为 eventName 的事件的监听器数组的末尾。不检查是否已添加 listener。多次调用传入相同的 eventNamelistener 组合将导致多次添加和调用 listener

¥Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

server.on('connection', (stream) => {
  console.log('someone connected!');
}); 

返回对 EventEmitter 的引用,以便可以链式调用。

¥Returns a reference to the EventEmitter, so that calls can be chained.

默认情况下,事件监听器按添加顺序调用。emitter.prependListener() 方法可用作将事件监听器添加到监听器数组开头的替代方法。

¥By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
//   b
//   aconst EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
//   b
//   a

emitter.once(eventName, listener)#

为名为 eventName 的事件添加一次性 listener 函数。下次触发 eventName 时,将移除此监听器,然后再调用。

¥Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

server.once('connection', (stream) => {
  console.log('Ah, we have our first user!');
}); 

返回对 EventEmitter 的引用,以便可以链式调用。

¥Returns a reference to the EventEmitter, so that calls can be chained.

默认情况下,事件监听器按添加顺序调用。emitter.prependOnceListener() 方法可用作将事件监听器添加到监听器数组开头的替代方法。

¥By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
//   b
//   aconst EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
//   b
//   a

emitter.prependListener(eventName, listener)#

listener 函数添加到名为 eventName 的事件的监听器数组的开头。不检查是否已添加 listener。多次调用传入相同的 eventNamelistener 组合将导致多次添加和调用 listener

¥Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

server.prependListener('connection', (stream) => {
  console.log('someone connected!');
}); 

返回对 EventEmitter 的引用,以便可以链式调用。

¥Returns a reference to the EventEmitter, so that calls can be chained.

emitter.prependOnceListener(eventName, listener)#

将名为 eventName 的事件的一次性 listener 函数添加到监听器数组的开头。下次触发 eventName 时,将移除此监听器,然后再调用。

¥Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

server.prependOnceListener('connection', (stream) => {
  console.log('Ah, we have our first user!');
}); 

返回对 EventEmitter 的引用,以便可以链式调用。

¥Returns a reference to the EventEmitter, so that calls can be chained.

emitter.removeAllListeners([eventName])#

删除所有监听器,或指定 eventName 的监听器。

¥Removes all listeners, or those of the specified eventName.

删除在代码其他地方添加的监听器是不好的做法,特别是当 EventEmitter 实例是由其他组件或模块(例如套接字或文件流)创建时。

¥It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

返回对 EventEmitter 的引用,以便可以链式调用。

¥Returns a reference to the EventEmitter, so that calls can be chained.

emitter.removeListener(eventName, listener)#

从名为 eventName 的事件的监听器数组中移除指定的 listener

¥Removes the specified listener from the listener array for the event named eventName.

const callback = (stream) => {
  console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback); 

removeListener() 最多从监听器数组中删除一个监听器实例。如果任何单个监听器已多次添加到指定 eventName 的监听器数组中,则必须多次调用 removeListener() 以删除每个实例。

¥removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

一旦事件被触发,则所有在触发时绑定到它的监听器都会被依次调用。这意味着在触发之后和最后一个监听器完成执行之前的任何 removeListener()removeAllListeners() 调用都不会将它们从正在进行的 emit() 中删除。后续事件按预期运行。

¥Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.

import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

const callbackA = () => {
  console.log('A');
  myEmitter.removeListener('event', callbackB);
};

const callbackB = () => {
  console.log('B');
};

myEmitter.on('event', callbackA);

myEmitter.on('event', callbackB);

// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
//   A
//   B

// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
//   Aconst EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

const callbackA = () => {
  console.log('A');
  myEmitter.removeListener('event', callbackB);
};

const callbackB = () => {
  console.log('B');
};

myEmitter.on('event', callbackA);

myEmitter.on('event', callbackB);

// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
//   A
//   B

// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
//   A

由于监听器是使用内部数组进行管理的,因此调用此方法将更改监听器被删除后注册的任何监听器的位置索引。这不会影响调用监听器的顺序,但这意味着需要重新创建 emitter.listeners() 方法返回的监听器数组的任何副本。

¥Because listeners are managed using an internal array, calling this will change the position indexes of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

当单个函数被多次添加为单个事件的句柄时(如下例所示),则 removeListener() 将删除最近添加的实例。在示例中,删除了 once('ping') 监听器:

¥When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

import { EventEmitter } from 'node:events';
const ee = new EventEmitter();

function pong() {
  console.log('pong');
}

ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);

ee.emit('ping');
ee.emit('ping');const EventEmitter = require('node:events');
const ee = new EventEmitter();

function pong() {
  console.log('pong');
}

ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);

ee.emit('ping');
ee.emit('ping');

返回对 EventEmitter 的引用,以便可以链式调用。

¥Returns a reference to the EventEmitter, so that calls can be chained.

emitter.setMaxListeners(n)#

默认情况下,如果为特定事件添加了超过 10 个监听器,EventEmitter 将打印警告。这是一个有用的默认值,有助于查找内存泄漏。emitter.setMaxListeners() 方法允许修改此特定 EventEmitter 实例的限制。该值可以设置为 Infinity(或 0)以指示无限数量的监听器。

¥By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

返回对 EventEmitter 的引用,以便可以链式调用。

¥Returns a reference to the EventEmitter, so that calls can be chained.

emitter.rawListeners(eventName)#

返回名为 eventName 的事件的监听器数组的副本,包括任何封装器(例如由 .once() 创建的封装器)。

¥Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));

// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];

// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();

// Logs "log once" to the console and removes the listener
logFnWrapper();

emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');

// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));

// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];

// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();

// Logs "log once" to the console and removes the listener
logFnWrapper();

emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');

// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');

emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])#

Symbol.for('nodejs.rejection') 方法被调用,以防在触发事件时发生 promise 拒绝,并且在触发器上启用了 captureRejections。可以使用 events.captureRejectionSymbol 代替 Symbol.for('nodejs.rejection')

¥The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').

import { EventEmitter, captureRejectionSymbol } from 'node:events';

class MyClass extends EventEmitter {
  constructor() {
    super({ captureRejections: true });
  }

  [captureRejectionSymbol](err, event, ...args) {
    console.log('rejection happened for', event, 'with', err, ...args);
    this.destroy(err);
  }

  destroy(err) {
    // Tear the resource down here.
  }
}const { EventEmitter, captureRejectionSymbol } = require('node:events');

class MyClass extends EventEmitter {
  constructor() {
    super({ captureRejections: true });
  }

  [captureRejectionSymbol](err, event, ...args) {
    console.log('rejection happened for', event, 'with', err, ...args);
    this.destroy(err);
  }

  destroy(err) {
    // Tear the resource down here.
  }
}

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:

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

events.errorMonitor#

此符号应用于安装仅监视 'error' 事件的监听器。在调用常规 'error' 监听器之前调用使用此符号安装的监听器。

¥This symbol shall be used to install a listener for only monitoring 'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.

一旦触发 'error' 事件,则使用此符号安装监听器不会改变行为。因此,如果没有安装常规的 'error' 监听器,则进程仍然会崩溃。

¥Installing a listener using this symbol does not change the behavior once an 'error' event is emitted. Therefore, the process will still crash if no regular 'error' listener is installed.

events.getEventListeners(emitterOrTarget, eventName)#

返回名为 eventName 的事件的监听器数组的副本。

¥Returns a copy of the array of listeners for the event named eventName.

对于 EventEmitter,这与在触发器上调用 .listeners 的行为完全相同。

¥For EventEmitters this behaves exactly the same as calling .listeners on the emitter.

对于 EventTarget,这是获取事件目标的事件监听器的唯一方法。这对于调试和诊断目的很有用。

¥For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

import { getEventListeners, EventEmitter } from 'node:events';

{
  const ee = new EventEmitter();
  const listener = () => console.log('Events are fun');
  ee.on('foo', listener);
  console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
  const et = new EventTarget();
  const listener = () => console.log('Events are fun');
  et.addEventListener('foo', listener);
  console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}const { getEventListeners, EventEmitter } = require('node:events');

{
  const ee = new EventEmitter();
  const listener = () => console.log('Events are fun');
  ee.on('foo', listener);
  console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
  const et = new EventTarget();
  const listener = () => console.log('Events are fun');
  et.addEventListener('foo', listener);
  console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}

events.getMaxListeners(emitterOrTarget)#

返回当前设置的最大监听器数量。

¥Returns the currently set max amount of listeners.

对于 EventEmitter,这与在触发器上调用 .getMaxListeners 的行为完全相同。

¥For EventEmitters this behaves exactly the same as calling .getMaxListeners on the emitter.

对于 EventTarget,这是为事件目标获取最大事件监听器的唯一方法。如果单个 EventTarget 上的事件处理程序数量超过最大设置,EventTarget 将打印警告。

¥For EventTargets this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.

import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';

{
  const ee = new EventEmitter();
  console.log(getMaxListeners(ee)); // 10
  setMaxListeners(11, ee);
  console.log(getMaxListeners(ee)); // 11
}
{
  const et = new EventTarget();
  console.log(getMaxListeners(et)); // 10
  setMaxListeners(11, et);
  console.log(getMaxListeners(et)); // 11
}const { getMaxListeners, setMaxListeners, EventEmitter } = require('node:events');

{
  const ee = new EventEmitter();
  console.log(getMaxListeners(ee)); // 10
  setMaxListeners(11, ee);
  console.log(getMaxListeners(ee)); // 11
}
{
  const et = new EventTarget();
  console.log(getMaxListeners(et)); // 10
  setMaxListeners(11, et);
  console.log(getMaxListeners(et)); // 11
}

events.once(emitter, name[, options])#

创建 Promise,其在 EventEmitter 触发给定事件时被履行,或者如果 EventEmitter 在等待时触发 'error' 则被拒绝。Promise 将使用触发给定事件的所有参数的数组解决。

¥Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

此方法是有意通用的,适用于 Web 平台 EventTarget 接口,它没有特殊的 'error' 事件语义,也不监听 'error' 事件。

¥This method is intentionally generic and works with the web platform EventTarget interface, which has no special 'error' event semantics and does not listen to the 'error' event.

import { once, EventEmitter } from 'node:events';
import process from 'node:process';

const ee = new EventEmitter();

process.nextTick(() => {
  ee.emit('myevent', 42);
});

const [value] = await once(ee, 'myevent');
console.log(value);

const err = new Error('kaboom');
process.nextTick(() => {
  ee.emit('error', err);
});

try {
  await once(ee, 'myevent');
} catch (err) {
  console.error('error happened', err);
}const { once, EventEmitter } = require('node:events');

async function run() {
  const ee = new EventEmitter();

  process.nextTick(() => {
    ee.emit('myevent', 42);
  });

  const [value] = await once(ee, 'myevent');
  console.log(value);

  const err = new Error('kaboom');
  process.nextTick(() => {
    ee.emit('error', err);
  });

  try {
    await once(ee, 'myevent');
  } catch (err) {
    console.error('error happened', err);
  }
}

run();

'error' 事件的特殊处理仅在 events.once() 用于等待另一个事件时使用。如果 events.once() 用于等待 error' 事件本身,则它将被视为任何其他类型的事件而无需特殊处理:

¥The special handling of the 'error' event is only used when events.once() is used to wait for another event. If events.once() is used to wait for the 'error' event itself, then it is treated as any other kind of event without special handling:

import { EventEmitter, once } from 'node:events';

const ee = new EventEmitter();

once(ee, 'error')
  .then(([err]) => console.log('ok', err.message))
  .catch((err) => console.error('error', err.message));

ee.emit('error', new Error('boom'));

// Prints: ok boomconst { EventEmitter, once } = require('node:events');

const ee = new EventEmitter();

once(ee, 'error')
  .then(([err]) => console.log('ok', err.message))
  .catch((err) => console.error('error', err.message));

ee.emit('error', new Error('boom'));

// Prints: ok boom

<AbortSignal> 可用于取消等待事件:

¥An <AbortSignal> can be used to cancel waiting for the event:

import { EventEmitter, once } from 'node:events';

const ee = new EventEmitter();
const ac = new AbortController();

async function foo(emitter, event, signal) {
  try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
  } catch (error) {
    if (error.name === 'AbortError') {
      console.error('Waiting for the event was canceled!');
    } else {
      console.error('There was an error', error.message);
    }
  }
}

foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!const { EventEmitter, once } = require('node:events');

const ee = new EventEmitter();
const ac = new AbortController();

async function foo(emitter, event, signal) {
  try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
  } catch (error) {
    if (error.name === 'AbortError') {
      console.error('Waiting for the event was canceled!');
    } else {
      console.error('There was an error', error.message);
    }
  }
}

foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!

等待 process.nextTick() 上触发的多个事件#

¥Awaiting multiple events emitted on process.nextTick()

当使用 events.once() 函数等待在同一批 process.nextTick() 操作中触发的多个事件时,或者同步触发多个事件时,有一个边缘情况值得注意。具体来说,因为 process.nextTick() 队列在 Promise 微任务队列之前被排空,并且因为 EventEmitter 同步触发所有事件,所以 events.once() 有可能遗漏事件。

¥There is an edge case worth noting when using the events.once() function to await multiple events emitted on in the same batch of process.nextTick() operations, or whenever multiple events are emitted synchronously. Specifically, because the process.nextTick() queue is drained before the Promise microtask queue, and because EventEmitter emits all events synchronously, it is possible for events.once() to miss an event.

import { EventEmitter, once } from 'node:events';
import process from 'node:process';

const myEE = new EventEmitter();

async function foo() {
  await once(myEE, 'bar');
  console.log('bar');

  // This Promise will never resolve because the 'foo' event will
  // have already been emitted before the Promise is created.
  await once(myEE, 'foo');
  console.log('foo');
}

process.nextTick(() => {
  myEE.emit('bar');
  myEE.emit('foo');
});

foo().then(() => console.log('done'));const { EventEmitter, once } = require('node:events');

const myEE = new EventEmitter();

async function foo() {
  await once(myEE, 'bar');
  console.log('bar');

  // This Promise will never resolve because the 'foo' event will
  // have already been emitted before the Promise is created.
  await once(myEE, 'foo');
  console.log('foo');
}

process.nextTick(() => {
  myEE.emit('bar');
  myEE.emit('foo');
});

foo().then(() => console.log('done'));

要捕获这两个事件,请在等待其中任何一个之前创建每个 Promise,然后就可以使用 Promise.all()Promise.race()Promise.allSettled()

¥To catch both events, create each of the Promises before awaiting either of them, then it becomes possible to use Promise.all(), Promise.race(), or Promise.allSettled():

import { EventEmitter, once } from 'node:events';
import process from 'node:process';

const myEE = new EventEmitter();

async function foo() {
  await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);
  console.log('foo', 'bar');
}

process.nextTick(() => {
  myEE.emit('bar');
  myEE.emit('foo');
});

foo().then(() => console.log('done'));const { EventEmitter, once } = require('node:events');

const myEE = new EventEmitter();

async function foo() {
  await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);
  console.log('foo', 'bar');
}

process.nextTick(() => {
  myEE.emit('bar');
  myEE.emit('foo');
});

foo().then(() => console.log('done'));

events.captureRejections#

值:<boolean>

¥Value: <boolean>

更改所有新的 EventEmitter 对象的默认 captureRejections 选项。

¥Change the default captureRejections option on all new EventEmitter objects.

events.captureRejectionSymbol#

值:Symbol.for('nodejs.rejection')

¥Value: Symbol.for('nodejs.rejection')

查看如何编写自定义 拒绝处理程序

¥See how to write a custom rejection handler.

events.listenerCount(emitter, eventName)#

稳定性: 0 - 已弃用:改用 emitter.listenerCount()

¥Stability: 0 - Deprecated: Use emitter.listenerCount() instead.

返回在给定 emitter 上注册的给定 eventName 的监听器数量的类方法。

¥A class method that returns the number of listeners for the given eventName registered on the given emitter.

import { EventEmitter, listenerCount } from 'node:events';

const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2const { EventEmitter, listenerCount } = require('node:events');

const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2

events.on(emitter, eventName[, options])#

  • emitter <EventEmitter>

  • eventName <string> | <symbol> 正在监听的事件的名称

    ¥eventName <string> | <symbol> The name of the event being listened for

  • options <Object>

    • signal <AbortSignal> 可用于取消等待事件。

      ¥signal <AbortSignal> Can be used to cancel awaiting events.

    • close - <string[]> 将结束迭代的事件的名称。

      ¥close - <string[]> Names of events that will end the iteration.

    • highWaterMark - <integer> 默认值:Number.MAX_SAFE_INTEGER 高水位线。每当缓冲的事件大小高于它时,触发器就会暂停。仅在实现 pause()resume() 方法的触发器上受支持。

      ¥highWaterMark - <integer> Default: Number.MAX_SAFE_INTEGER The high watermark. The emitter is paused every time the size of events being buffered is higher than it. Supported only on emitters implementing pause() and resume() methods.

    • lowWaterMark - <integer> 默认值:1 低水位线。每当缓冲的事件大小低于它时,触发器就会恢复。仅在实现 pause()resume() 方法的触发器上受支持。

      ¥lowWaterMark - <integer> Default: 1 The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. Supported only on emitters implementing pause() and resume() methods.

  • 返回:<AsyncIterator> 迭代 emitter 触发的 eventName 事件

    ¥Returns: <AsyncIterator> that iterates eventName events emitted by the emitter

import { on, EventEmitter } from 'node:events';
import process from 'node:process';

const ee = new EventEmitter();

// Emit later on
process.nextTick(() => {
  ee.emit('foo', 'bar');
  ee.emit('foo', 42);
});

for await (const event of on(ee, 'foo')) {
  // The execution of this inner block is synchronous and it
  // processes one event at a time (even with await). Do not use
  // if concurrent execution is required.
  console.log(event); // prints ['bar'] [42]
}
// Unreachable hereconst { on, EventEmitter } = require('node:events');

(async () => {
  const ee = new EventEmitter();

  // Emit later on
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
  }
  // Unreachable here
})();

返回迭代 eventName 事件的 AsyncIterator。如果 EventEmitter 触发 'error',则将抛出错误。它在退出循环时删除所有监听器。每次迭代返回的 value 是由触发的事件参数组成的数组。

¥Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

<AbortSignal> 可用于取消对事件的等待:

¥An <AbortSignal> can be used to cancel waiting on events:

import { on, EventEmitter } from 'node:events';
import process from 'node:process';

const ac = new AbortController();

(async () => {
  const ee = new EventEmitter();

  // Emit later on
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
  }
  // Unreachable here
})();

process.nextTick(() => ac.abort());const { on, EventEmitter } = require('node:events');

const ac = new AbortController();

(async () => {
  const ee = new EventEmitter();

  // Emit later on
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
  }
  // Unreachable here
})();

process.nextTick(() => ac.abort());

events.setMaxListeners(n[, ...eventTargets])#

import { setMaxListeners, EventEmitter } from 'node:events';

const target = new EventTarget();
const emitter = new EventEmitter();

setMaxListeners(5, target, emitter);const {
  setMaxListeners,
  EventEmitter,
} = require('node:events');

const target = new EventTarget();
const emitter = new EventEmitter();

setMaxListeners(5, target, emitter);

events.addAbortListener(signal, listener)#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

在提供的 signal 上监听一次 abort 事件。

¥Listens once to the abort event on the provided signal.

监听中止信号上的 abort 事件是不安全的,并且可能导致资源泄漏,因为具有该信号的另一个第三方可以调用 e.stopImmediatePropagation()。不幸的是 Node.js 无法改变这一点,因为它违反了 Web 标准。此外,原始 API 很容易忘记删除监听器。

¥Listening to the abort event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call e.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.

此 API 允许在 Node.js API 中安全地使用 AbortSignal,通过监听事件来解决这两个问题,这样 stopImmediatePropagation 就不会阻止监听器运行。

¥This API allows safely using AbortSignals in Node.js APIs by solving these two issues by listening to the event such that stopImmediatePropagation does not prevent the listener from running.

返回一次性内容,以便更轻松地取消订阅。

¥Returns a disposable so that it may be unsubscribed from more easily.

const { addAbortListener } = require('node:events');

function example(signal) {
  let disposable;
  try {
    signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
    disposable = addAbortListener(signal, (e) => {
      // Do something when signal is aborted.
    });
  } finally {
    disposable?.[Symbol.dispose]();
  }
}import { addAbortListener } from 'node:events';

function example(signal) {
  let disposable;
  try {
    signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
    disposable = addAbortListener(signal, (e) => {
      // Do something when signal is aborted.
    });
  } finally {
    disposable?.[Symbol.dispose]();
  }
}

类:events.EventEmitterAsyncResource extends EventEmitter#

¥Class: events.EventEmitterAsyncResource extends EventEmitter

为需要手动异步跟踪的 EventEmitter 集成 EventEmitter<AsyncResource>。具体来说,events.EventEmitterAsyncResource 实例触发的所有事件都将在其 异步上下文 中运行。

¥Integrates EventEmitter with <AsyncResource> for EventEmitters that require manual async tracking. Specifically, all events emitted by instances of events.EventEmitterAsyncResource will run within its async context.

import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
import { notStrictEqual, strictEqual } from 'node:assert';
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';

// Async tracking tooling will identify this as 'Q'.
const ee1 = new EventEmitterAsyncResource({ name: 'Q' });

// 'foo' listeners will run in the EventEmitters async context.
ee1.on('foo', () => {
  strictEqual(executionAsyncId(), ee1.asyncId);
  strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
});

const ee2 = new EventEmitter();

// 'foo' listeners on ordinary EventEmitters that do not track async
// context, however, run in the same async context as the emit().
ee2.on('foo', () => {
  notStrictEqual(executionAsyncId(), ee2.asyncId);
  notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
});

Promise.resolve().then(() => {
  ee1.emit('foo');
  ee2.emit('foo');
});const { EventEmitterAsyncResource, EventEmitter } = require('node:events');
const { notStrictEqual, strictEqual } = require('node:assert');
const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');

// Async tracking tooling will identify this as 'Q'.
const ee1 = new EventEmitterAsyncResource({ name: 'Q' });

// 'foo' listeners will run in the EventEmitters async context.
ee1.on('foo', () => {
  strictEqual(executionAsyncId(), ee1.asyncId);
  strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
});

const ee2 = new EventEmitter();

// 'foo' listeners on ordinary EventEmitters that do not track async
// context, however, run in the same async context as the emit().
ee2.on('foo', () => {
  notStrictEqual(executionAsyncId(), ee2.asyncId);
  notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
});

Promise.resolve().then(() => {
  ee1.emit('foo');
  ee2.emit('foo');
});

EventEmitterAsyncResource 类具有与 EventEmitterAsyncResource 本身相同的方法和选项。

¥The EventEmitterAsyncResource class has the same methods and takes the same options as EventEmitter and AsyncResource themselves.

new events.EventEmitterAsyncResource([options])#

  • options <Object>

    • captureRejections <boolean> 它启用 自动捕获 promise 拒绝。默认值:false

      ¥captureRejections <boolean> It enables automatic capturing of promise rejection. Default: false.

    • name <string> 异步事件的类型。默认值:new.target.name

      ¥name <string> The type of async event. Default: new.target.name.

    • triggerAsyncId <number> 创建此异步事件的执行上下文的 ID。默认值:executionAsyncId()

      ¥triggerAsyncId <number> The ID of the execution context that created this async event. Default: executionAsyncId().

    • requireManualDestroy <boolean> 如果设置为 true,则当对象被垃圾回收时禁用 emitDestroy。这通常不需要设置(即使手动调用 emitDestroy),除非检索到资源的 asyncId 并调用敏感 API 的 emitDestroy。当设置为 false 时,则只有在至少有一个活动的 destroy 钩子时才会调用 emitDestroy 垃圾回收。默认值:false

      ¥requireManualDestroy <boolean> If set to true, disables emitDestroy when the object is garbage collected. This usually does not need to be set (even if emitDestroy is called manually), unless the resource's asyncId is retrieved and the sensitive API's emitDestroy is called with it. When set to false, the emitDestroy call on garbage collection will only take place if there is at least one active destroy hook. Default: false.

eventemitterasyncresource.asyncId#

  • 类型:<number> 分配给资源的唯一 asyncId

    ¥Type: <number> The unique asyncId assigned to the resource.

eventemitterasyncresource.asyncResource#

返回的 AsyncResource 对象具有额外的 eventEmitter 属性,提供对此 EventEmitterAsyncResource 的引用。

¥The returned AsyncResource object has an additional eventEmitter property that provides a reference to this EventEmitterAsyncResource.

eventemitterasyncresource.emitDestroy()#

调用所有的 destroy 钩子。这应该只被调用一次。如果多次调用,则会报错。这必须手动调用。如果资源留给 GC 收集,则永远不会调用 destroy 钩子。

¥Call all destroy hooks. This should only ever be called once. An error will be thrown if it is called more than once. This must be manually called. If the resource is left to be collected by the GC then the destroy hooks will never be called.

eventemitterasyncresource.triggerAsyncId#

  • 类型:<number> 传给 AsyncResource 构造函数的同一个 triggerAsyncId

    ¥Type: <number> The same triggerAsyncId that is passed to the AsyncResource constructor.

EventTargetEvent API#

¥EventTarget and Event API

EventTargetEvent 对象是 EventTarget 网络应用接口 的特定于 Node.js 的实现,由一些 Node.js 核心 API 公开。

¥The EventTarget and Event objects are a Node.js-specific implementation of the EventTarget Web API that are exposed by some Node.js core APIs.

const target = new EventTarget();

target.addEventListener('foo', (event) => {
  console.log('foo event happened!');
}); 

Node.js EventTarget 与 DOM EventTarget#

¥Node.js EventTarget vs. DOM EventTarget

Node.js EventTargetEventTarget 网络应用接口 之间有两个主要区别:

¥There are two key differences between the Node.js EventTarget and the EventTarget Web API:

  1. 尽管 DOM EventTarget 实例可能是分层的,但 Node.js 中没有分层和事件传播的概念。也就是说,调度到 EventTarget 的事件不会通过嵌套目标对象的层次结构传播,这些目标对象可能每个都有自己的事件句柄集。

    ¥Whereas DOM EventTarget instances may be hierarchical, there is no concept of hierarchy and event propagation in Node.js. That is, an event dispatched to an EventTarget does not propagate through a hierarchy of nested target objects that may each have their own set of handlers for the event.

  2. 在 Node.js EventTarget 中,如果事件监听器是一个异步函数或返回一个 Promise,而返回的 Promise 拒绝,则拒绝被自动捕获并以与同步抛出的监听器相同的方式处理(详见 EventTarget 错误处理)。

    ¥In the Node.js EventTarget, if an event listener is an async function or returns a Promise, and the returned Promise rejects, the rejection is automatically captured and handled the same way as a listener that throws synchronously (see EventTarget error handling for details).

NodeEventTargetEventEmitter#

¥NodeEventTarget vs. EventEmitter

NodeEventTarget 对象实现了 EventEmitter API 的修改子集,允许它在某些情况下模拟 EventEmitterNodeEventTarget 不是 EventEmitter 的实例,在大多数情况下不能用来代替 EventEmitter

¥The NodeEventTarget object implements a modified subset of the EventEmitter API that allows it to closely emulate an EventEmitter in certain situations. A NodeEventTarget is not an instance of EventEmitter and cannot be used in place of an EventEmitter in most cases.

  1. EventEmitter 不同,任何给定的 listener 最多可以在每个事件 type 中注册一次。尝试多次注册 listener 将被忽略。

    ¥Unlike EventEmitter, any given listener can be registered at most once per event type. Attempts to register a listener multiple times are ignored.

  2. NodeEventTarget 不模拟完整的 EventEmitter API。特别是 prependListener()prependOnceListener()rawListeners()errorMonitor API 未被模拟。'newListener''removeListener' 事件也不会触发。

    ¥The NodeEventTarget does not emulate the full EventEmitter API. Specifically the prependListener(), prependOnceListener(), rawListeners(), and errorMonitor APIs are not emulated. The 'newListener' and 'removeListener' events will also not be emitted.

  3. NodeEventTarget 没有为类型为 'error' 的事件实现任何特殊的默认行为。

    ¥The NodeEventTarget does not implement any special default behavior for events with type 'error'.

  4. NodeEventTarget 支持 EventListener 对象以及作为所有事件类型句柄的函数。

    ¥The NodeEventTarget supports EventListener objects as well as functions as handlers for all event types.

事件监听器#

¥Event listener

为事件 type 注册的事件监听器可以是 JavaScript 函数,也可以是具有值为函数的 handleEvent 属性的对象。

¥Event listeners registered for an event type may either be JavaScript functions or objects with a handleEvent property whose value is a function.

在任何一种情况下,句柄函数都是通过传给 eventTarget.dispatchEvent() 函数的 event 参数调用的。

¥In either case, the handler function is invoked with the event argument passed to the eventTarget.dispatchEvent() function.

异步函数可用作事件监听器。如果异步处理函数拒绝,则将按照 EventTarget 错误处理 中的描述捕获和处理拒绝。

¥Async functions may be used as event listeners. If an async handler function rejects, the rejection is captured and handled as described in EventTarget error handling.

句柄函数抛出的错误不会阻止其他句柄被调用。

¥An error thrown by one handler function does not prevent the other handlers from being invoked.

句柄函数的返回值会被忽略。

¥The return value of a handler function is ignored.

句柄始终按照其添加的顺序被调用。

¥Handlers are always invoked in the order they were added.

句柄函数可能会改变 event 对象。

¥Handler functions may mutate the event object.

function handler1(event) {
  console.log(event.type);  // Prints 'foo'
  event.a = 1;
}

async function handler2(event) {
  console.log(event.type);  // Prints 'foo'
  console.log(event.a);  // Prints 1
}

const handler3 = {
  handleEvent(event) {
    console.log(event.type);  // Prints 'foo'
  },
};

const handler4 = {
  async handleEvent(event) {
    console.log(event.type);  // Prints 'foo'
  },
};

const target = new EventTarget();

target.addEventListener('foo', handler1);
target.addEventListener('foo', handler2);
target.addEventListener('foo', handler3);
target.addEventListener('foo', handler4, { once: true }); 

EventTarget 错误处理#

¥EventTarget error handling

当注册的事件监听器抛出错误(或返回拒绝的 Promise)时,默认情况下,错误将被视为 process.nextTick() 上的未捕获异常。这意味着 EventTarget 中未捕获的异常将默认终止 Node.js 进程。

¥When a registered event listener throws (or returns a Promise that rejects), by default the error is treated as an uncaught exception on process.nextTick(). This means uncaught exceptions in EventTargets will terminate the Node.js process by default.

在事件监听器中抛出不会阻止调用其他已注册的处理程序。

¥Throwing within an event listener will not stop the other registered handlers from being invoked.

EventTarget 没有为 'error' 类型的事件(如 EventEmitter)实现任何特殊的默认处理。

¥The EventTarget does not implement any special default handling for 'error' type events like EventEmitter.

当前错误在到达 process.on('uncaughtException') 之前首先转发到 process.on('error') 事件。此行为已弃用,并将在未来版本中更改,以使 EventTarget 与其他 Node.js API 保持一致。任何依赖 process.on('error') 事件的代码都应与新行为保持一致。

¥Currently errors are first forwarded to the process.on('error') event before reaching process.on('uncaughtException'). This behavior is deprecated and will change in a future release to align EventTarget with other Node.js APIs. Any code relying on the process.on('error') event should be aligned with the new behavior.

类:Event#

¥Class: Event

Event 对象是 Event 网络应用接口 的改编版。实例由 Node.js 在内部创建。

¥The Event object is an adaptation of the Event Web API. Instances are created internally by Node.js.

event.bubbles#

这在 Node.js 中没有使用,纯粹是为了完整性而提供的。

¥This is not used in Node.js and is provided purely for completeness.

event.cancelBubble#

稳定性: 3 - 旧版:改用 event.stopPropagation()

¥Stability: 3 - Legacy: Use event.stopPropagation() instead.

如果设置为 true,则为 event.stopPropagation() 的别名。这在 Node.js 中没有使用,纯粹是为了完整性而提供的。

¥Alias for event.stopPropagation() if set to true. This is not used in Node.js and is provided purely for completeness.

event.cancelable#
  • 类型:<boolean> 如果事件是使用 cancelable 选项创建的,则为真。

    ¥Type: <boolean> True if the event was created with the cancelable option.

event.composed#

这在 Node.js 中没有使用,纯粹是为了完整性而提供的。

¥This is not used in Node.js and is provided purely for completeness.

event.composedPath()#

返回包含当前 EventTarget 作为唯一条目的数组,如果未调度事件则返回空数组。这在 Node.js 中没有使用,纯粹是为了完整性而提供的。

¥Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness.

event.currentTarget#

event.target 的别名。

¥Alias for event.target.

event.defaultPrevented#

如果 cancelabletrueevent.preventDefault() 已被调用,则为 true

¥Is true if cancelable is true and event.preventDefault() has been called.

event.eventPhase#
  • 类型:<number> 事件未被调度时返回 0,事件被调度时返回 2

    ¥Type: <number> Returns 0 while an event is not being dispatched, 2 while it is being dispatched.

这在 Node.js 中没有使用,纯粹是为了完整性而提供的。

¥This is not used in Node.js and is provided purely for completeness.

event.initEvent(type[, bubbles[, cancelable]])#

稳定性: 3 - 旧版:WHATWG 规范认为它已弃用,用户根本不应使用它。

¥Stability: 3 - Legacy: The WHATWG spec considers it deprecated and users shouldn't use it at all.

事件构造函数冗余且无法设置 composed。这在 Node.js 中没有使用,纯粹是为了完整性而提供的。

¥Redundant with event constructors and incapable of setting composed. This is not used in Node.js and is provided purely for completeness.

event.isTrusted#

<AbortSignal> "abort" 事件是在 isTrusted 设置为 true 的情况下触发的。在所有其他情况下,该值为 false

¥The <AbortSignal> "abort" event is emitted with isTrusted set to true. The value is false in all other cases.

event.preventDefault()#

如果 cancelabletrue,则将 defaultPrevented 属性设置为 true

¥Sets the defaultPrevented property to true if cancelable is true.

event.returnValue#

稳定性: 3 - 旧版:改用 event.defaultPrevented

¥Stability: 3 - Legacy: Use event.defaultPrevented instead.

  • 类型:<boolean> 如果事件尚未取消,则为真。

    ¥Type: <boolean> True if the event has not been canceled.

event.returnValue 的值总是与 event.defaultPrevented 相反。这在 Node.js 中没有使用,纯粹是为了完整性而提供的。

¥The value of event.returnValue is always the opposite of event.defaultPrevented. This is not used in Node.js and is provided purely for completeness.

event.srcElement#

稳定性: 3 - 旧版:改用 event.target

¥Stability: 3 - Legacy: Use event.target instead.

event.target 的别名。

¥Alias for event.target.

event.stopImmediatePropagation()#

当前事件监听器完成后停止调用。

¥Stops the invocation of event listeners after the current one completes.

event.stopPropagation()#

这在 Node.js 中没有使用,纯粹是为了完整性而提供的。

¥This is not used in Node.js and is provided purely for completeness.

event.target#

event.timeStamp#

创建 Event 对象时的毫秒时间戳。

¥The millisecond timestamp when the Event object was created.

event.type#

事件类型标识符。

¥The event type identifier.

类:EventTarget#

¥Class: EventTarget

eventTarget.addEventListener(type, listener[, options])#
  • type <string>

  • listener <Function> | <EventListener>

  • options <Object>

    • once <boolean> 当为 true 时,监听器在第一次调用时自动移除。默认值:false

      ¥once <boolean> When true, the listener is automatically removed when it is first invoked. Default: false.

    • passive <boolean> 当为 true 时,提示监听器不会调用 Event 对象的 preventDefault() 方法。默认值:false

      ¥passive <boolean> When true, serves as a hint that the listener will not call the Event object's preventDefault() method. Default: false.

    • capture <boolean> Node.js 不直接使用。为 API 完整性而添加。默认值:false

      ¥capture <boolean> Not directly used by Node.js. Added for API completeness. Default: false.

    • signal <AbortSignal> 当调用给定的 AbortSignal 对象的 abort() 方法时,则监听器将被移除。

      ¥signal <AbortSignal> The listener will be removed when the given AbortSignal object's abort() method is called.

type 事件添加新的句柄。对于每个 type 和每个 capture 选项值,任何给定的 listener 仅添加一次。

¥Adds a new handler for the type event. Any given listener is added only once per type and per capture option value.

如果 once 选项为 true,则在下一次调度 type 事件后移除 listener

¥If the once option is true, the listener is removed after the next time a type event is dispatched.

除了按照 EventTarget 规范跟踪注册的事件监听器之外,Node.js 不会以任何功能方式使用 capture 选项。具体来说,capture 选项在注册 listener 时用作键的一部分。任何单独的 listener 都可以与 capture = false 添加一次,与 capture = true 添加一次。

¥The capture option is not used by Node.js in any functional way other than tracking registered event listeners per the EventTarget specification. Specifically, the capture option is used as part of the key when registering a listener. Any individual listener may be added once with capture = false, and once with capture = true.

function handler(event) {}

const target = new EventTarget();
target.addEventListener('foo', handler, { capture: true });  // first
target.addEventListener('foo', handler, { capture: false }); // second

// Removes the second instance of handler
target.removeEventListener('foo', handler);

// Removes the first instance of handler
target.removeEventListener('foo', handler, { capture: true }); 

eventTarget.dispatchEvent(event)#
  • event <Event>

  • 返回:<boolean> 如果任一事件的 cancelable 属性值为 false 或者未调用其 preventDefault() 方法,则为 true,否则为 false

    ¥Returns: <boolean> true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, otherwise false.

event 调度到 event.type 的句柄列表。

¥Dispatches the event to the list of handlers for event.type.

注册的事件监听器按照注册的顺序同步地调用。

¥The registered event listeners is synchronously invoked in the order they were registered.

eventTarget.removeEventListener(type, listener[, options])#

从事件 type 的句柄列表中删除 listener

¥Removes the listener from the list of handlers for event type.

类:CustomEvent#

¥Class: CustomEvent

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

CustomEvent 对象是 CustomEvent 网络应用接口 的改编版。实例由 Node.js 在内部创建。

¥The CustomEvent object is an adaptation of the CustomEvent Web API. Instances are created internally by Node.js.

event.detail#

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

  • 类型:<any> 返回初始化时传入的自定义数据。

    ¥Type: <any> Returns custom data passed when initializing.

只读。

¥Read-only.

类:NodeEventTarget#

¥Class: NodeEventTarget

NodeEventTargetEventTarget 的 Node.js 特定扩展,它模拟了 EventEmitter API 的子集。

¥The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API.

nodeEventTarget.addListener(type, listener)#

EventTarget 类的 Node.js 特定扩展,可模拟等效的 EventEmitter API。addListener()addEventListener() 之间的唯一区别是 addListener() 将返回对 EventTarget 的引用。

¥Node.js-specific extension to the EventTarget class that emulates the equivalent EventEmitter API. The only difference between addListener() and addEventListener() is that addListener() will return a reference to the EventTarget.

nodeEventTarget.emit(type, arg)#
  • type <string>

  • arg <any>

  • 返回:<boolean> 如果为 type 注册的事件监听器存在,则为 true,否则为 false

    ¥Returns: <boolean> true if event listeners registered for the type exist, otherwise false.

EventTarget 类的 Node.js 特定扩展,将 arg 分派到 type 的处理程序列表。

¥Node.js-specific extension to the EventTarget class that dispatches the arg to the list of handlers for type.

nodeEventTarget.eventNames()#

Node.js 特定于 EventTarget 类的扩展,它返回事件 type 名称的数组,事件监听器注册了这些名称。

¥Node.js-specific extension to the EventTarget class that returns an array of event type names for which event listeners are registered.

nodeEventTarget.listenerCount(type)#

EventTarget 类的 Node.js 特定扩展,返回为 type 注册的事件监听器的数量。

¥Node.js-specific extension to the EventTarget class that returns the number of event listeners registered for the type.

nodeEventTarget.setMaxListeners(n)#

EventTarget 类的 Node.js 特定扩展,将最大事件监听器的数量设置为 n

¥Node.js-specific extension to the EventTarget class that sets the number of max event listeners as n.

nodeEventTarget.getMaxListeners()#

返回最大事件监听器数量的 EventTarget 类的 Node.js 特定扩展。

¥Node.js-specific extension to the EventTarget class that returns the number of max event listeners.

nodeEventTarget.off(type, listener[, options])#

eventTarget.removeEventListener() 的 Node.js 特定别名。

¥Node.js-specific alias for eventTarget.removeEventListener().

nodeEventTarget.on(type, listener)#

eventTarget.addEventListener() 的 Node.js 特定别名。

¥Node.js-specific alias for eventTarget.addEventListener().

nodeEventTarget.once(type, listener)#

EventTarget 类的 Node.js 特定扩展,它为给定的事件 type 添加了 once 监听器。这相当于调用 on 并将 once 选项设置为 true

¥Node.js-specific extension to the EventTarget class that adds a once listener for the given event type. This is equivalent to calling on with the once option set to true.

nodeEventTarget.removeAllListeners([type])#

EventTarget 类的 Node.js 特定扩展。如果指定了 type,则删除 type 的所有注册监听器,否则删除所有注册的监听器。

¥Node.js-specific extension to the EventTarget class. If type is specified, removes all registered listeners for type, otherwise removes all registered listeners.

nodeEventTarget.removeListener(type, listener[, options])#

Node.js 特定于 EventTarget 类的扩展,用于删除给定 typelistenerremoveListener()removeEventListener() 之间的唯一区别是 removeListener() 将返回对 EventTarget 的引用。

¥Node.js-specific extension to the EventTarget class that removes the listener for the given type. The only difference between removeListener() and removeEventListener() is that removeListener() will return a reference to the EventTarget.