- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
Node.js v18.20.0 文档
- Node.js v18.20.0
-
目录
- 事件
- 将参数和
this
传递给监听器 - 异步与同步
- 只处理一次事件
- 错误事件
- 捕获对 promise 的拒绝
- 类:
EventEmitter
- 事件:
'newListener'
- 事件:
'removeListener'
emitter.addListener(eventName, listener)
emitter.emit(eventName[, ...args])
emitter.eventNames()
emitter.getMaxListeners()
emitter.listenerCount(eventName[, listener])
emitter.listeners(eventName)
emitter.off(eventName, listener)
emitter.on(eventName, listener)
emitter.once(eventName, listener)
emitter.prependListener(eventName, listener)
emitter.prependOnceListener(eventName, listener)
emitter.removeAllListeners([eventName])
emitter.removeListener(eventName, listener)
emitter.setMaxListeners(n)
emitter.rawListeners(eventName)
emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])
- 事件:
events.defaultMaxListeners
events.errorMonitor
events.getEventListeners(emitterOrTarget, eventName)
events.getMaxListeners(emitterOrTarget)
events.once(emitter, name[, options])
events.captureRejections
events.captureRejectionSymbol
events.listenerCount(emitter, eventName)
events.on(emitter, eventName[, options])
events.setMaxListeners(n[, ...eventTargets])
events.addAbortListener(signal, resource)
- 类:
events.EventEmitterAsyncResource extends EventEmitter
EventTarget
和Event
API- Node.js
EventTarget
与 DOMEventTarget
NodeEventTarget
与EventEmitter
- 事件监听器
EventTarget
错误处理- 类:
Event
event.bubbles
event.cancelBubble
event.cancelable
event.composed
event.composedPath()
event.currentTarget
event.defaultPrevented
event.eventPhase
event.isTrusted
event.preventDefault()
event.returnValue
event.srcElement
event.stopImmediatePropagation()
event.stopPropagation()
event.target
event.timeStamp
event.type
- 类:
EventTarget
- 类:
CustomEvent
- 类:
NodeEventTarget
nodeEventTarget.addListener(type, listener)
nodeEventTarget.emit(type, arg)
nodeEventTarget.eventNames()
nodeEventTarget.listenerCount(type)
nodeEventTarget.setMaxListeners(n)
nodeEventTarget.getMaxListeners()
nodeEventTarget.off(type, listener[, options])
nodeEventTarget.on(type, listener)
nodeEventTarget.once(type, listener)
nodeEventTarget.removeAllListeners([type])
nodeEventTarget.removeListener(type, listener[, options])
- Node.js
- 将参数和
- 事件
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- 其他版本
事件#
¥Events
¥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(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(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 {}
});
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: 2
const 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');
// Ignored
const 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.js
const 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 error
const 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.js
const { 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 EventEmitter
s emit the event 'newListener'
when new listeners are
added and 'removeListener'
when existing listeners are removed.
它支持以下的选项:
¥It supports the following option:
-
captureRejections
<boolean> 它启用 自动捕获 promise 拒绝。默认值:false
。¥
captureRejections
<boolean> It enables automatic capturing of promise rejection. Default:false
.
事件:'newListener'
#
¥Event: 'newListener'
-
eventName
<string> | <symbol> 正在监听的事件的名称¥
eventName
<string> | <symbol> The name of the event being listened for -
listener
<Function> 事件处理函数¥
listener
<Function> The event handler function
在将监听器添加到其内部监听器数组之前,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
// A
const 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'
-
listener
<Function> 事件处理函数¥
listener
<Function> The event handler function
'removeListener'
事件在 listener
被删除后触发。
¥The 'removeListener'
event is emitted after the listener
is removed.
emitter.addListener(eventName, listener)
#
-
listener
<Function>
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 listener
const 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 Symbol
s.
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
<string> | <symbol> 正在监听的事件的名称¥
eventName
<string> | <symbol> The name of the event being listened for -
listener
<Function> 事件处理函数¥
listener
<Function> The event handler function -
返回:<integer>
¥Returns: <integer>
返回监听名为 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)
#
-
返回:<Function[]>
¥Returns: <Function[]>
返回名为 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)
#
-
listener
<Function> -
¥Returns: <EventEmitter>
¥Alias for emitter.removeListener()
.
emitter.on(eventName, listener)
#
-
listener
<Function> 回调函数¥
listener
<Function> The callback function -
¥Returns: <EventEmitter>
将 listener
函数添加到名为 eventName
的事件的监听器数组的末尾。不检查是否已添加 listener
。多次调用传入相同的 eventName
和 listener
组合将导致多次添加和调用 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
// a
const 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)
#
-
listener
<Function> 回调函数¥
listener
<Function> The callback function -
¥Returns: <EventEmitter>
为名为 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
// a
const 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
<Function> 回调函数¥
listener
<Function> The callback function -
¥Returns: <EventEmitter>
将 listener
函数添加到名为 eventName
的事件的监听器数组的开头。不检查是否已添加 listener
。多次调用传入相同的 eventName
和 listener
组合将导致多次添加和调用 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)
#
-
listener
<Function> 回调函数¥
listener
<Function> The callback function -
¥Returns: <EventEmitter>
将名为 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])
#
-
¥Returns: <EventEmitter>
删除所有监听器,或指定 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)
#
-
listener
<Function> -
¥Returns: <EventEmitter>
从名为 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:
// A
const 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 indices 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)
#
-
¥Returns: <EventEmitter>
默认情况下,如果为特定事件添加了超过 10
个监听器,EventEmitter
将打印警告。这是一个有用的默认值,有助于查找内存泄漏。emitter.setMaxListeners()
方法允许修改此特定 EventEmitter
实例的限制。该值可以设置为 Infinity
(或 0
)以指示无限数量的监听器。
¥By default EventEmitter
s 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)
#
-
返回:<Function[]>
¥Returns: <Function[]>
返回名为 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')
进行检查,并将具有额外的 emitter
、type
和 count
属性,分别指事件触发器实例、事件名称和附加监听器的数量。其 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)
#
-
emitterOrTarget
<EventEmitter> | <EventTarget> -
返回:<Function[]>
¥Returns: <Function[]>
返回名为 eventName
的事件的监听器数组的副本。
¥Returns a copy of the array of listeners for the event named eventName
.
对于 EventEmitter
,这与在触发器上调用 .listeners
的行为完全相同。
¥For EventEmitter
s this behaves exactly the same as calling .listeners
on
the emitter.
对于 EventTarget
,这是获取事件目标的事件监听器的唯一方法。这对于调试和诊断目的很有用。
¥For EventTarget
s 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)
#
-
emitterOrTarget
<EventEmitter> | <EventTarget> -
返回:<number>
¥Returns: <number>
返回当前设置的最大监听器数量。
¥Returns the currently set max amount of listeners.
对于 EventEmitter
,这与在触发器上调用 .getMaxListeners
的行为完全相同。
¥For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
the emitter.
对于 EventTarget
,这是为事件目标获取最大事件监听器的唯一方法。如果单个 EventTarget 上的事件处理程序数量超过最大设置,EventTarget 将打印警告。
¥For EventTarget
s 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])
#
-
emitter
<EventEmitter> -
name
<string> -
options
<Object>-
signal
<AbortSignal> 可用于取消等待事件。¥
signal
<AbortSignal> Can be used to cancel waiting for the event.
-
-
返回:<Promise>
¥Returns: <Promise>
创建 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 boom
const { 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
#
¥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)
#
emitter.listenerCount()
。¥Stability: 0 - Deprecated: Use emitter.listenerCount()
instead.
-
emitter
<EventEmitter> 要查询的触发器¥
emitter
<EventEmitter> The emitter to query
返回在给定 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: 2
const { 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.
-
-
返回:<AsyncIterator> 迭代
emitter
触发的eventName
事件¥Returns: <AsyncIterator> that iterates
eventName
events emitted by theemitter
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 here
const { 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])
#
-
n
<number> 非负的数值。每个EventTarget
事件的最大监听器数。¥
n
<number> A non-negative number. The maximum number of listeners perEventTarget
event. -
...eventsTargets
<EventTarget[]> | <EventEmitter[]> 零个或多个 <EventTarget> 或 <EventEmitter> 实例。如果没有指定,则n
被设置为所有新创建的 <EventTarget> 和 <EventEmitter> 对象的默认最大值。¥
...eventsTargets
<EventTarget[]> | <EventEmitter[]> Zero or more <EventTarget> or <EventEmitter> instances. If none are specified,n
is set as the default max for all newly created <EventTarget> and <EventEmitter> objects.
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, resource)
#
¥Stability: 1 - Experimental
-
signal
<AbortSignal> -
listener
<Function> | <EventListener> -
返回:<Disposable> 删除
abort
监听器。¥Returns: <Disposable> that removes the
abort
listener.
在提供的 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 AbortSignal
s 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 EventEmitter
s 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
类具有与 EventEmitter
和 AsyncResource
本身相同的方法和选项。
¥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 totrue
, disablesemitDestroy
when the object is garbage collected. This usually does not need to be set (even ifemitDestroy
is called manually), unless the resource'sasyncId
is retrieved and the sensitive API'semitDestroy
is called with it. When set tofalse
, theemitDestroy
call on garbage collection will only take place if there is at least one activedestroy
hook. Default:false
.
-
eventemitterasyncresource.asyncId
#
eventemitterasyncresource.asyncResource
#
-
类型:底层 <AsyncResource>。
¥Type: The underlying <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
#
EventTarget
和 Event
API#
¥EventTarget
and Event
API
EventTarget
和 Event
对象是 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 EventTarget
和 EventTarget
网络应用接口 之间有两个主要区别:
¥There are two key differences between the Node.js EventTarget
and the
EventTarget
Web API:
-
尽管 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 anEventTarget
does not propagate through a hierarchy of nested target objects that may each have their own set of handlers for the event. -
在 Node.js
EventTarget
中,如果事件监听器是一个异步函数或返回一个Promise
,而返回的Promise
拒绝,则拒绝被自动捕获并以与同步抛出的监听器相同的方式处理(详见EventTarget
错误处理)。¥In the Node.js
EventTarget
, if an event listener is an async function or returns aPromise
, and the returnedPromise
rejects, the rejection is automatically captured and handled the same way as a listener that throws synchronously (seeEventTarget
error handling for details).
NodeEventTarget
与 EventEmitter
#
¥NodeEventTarget
vs. EventEmitter
NodeEventTarget
对象实现了 EventEmitter
API 的修改子集,允许它在某些情况下模拟 EventEmitter
。NodeEventTarget
不是 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.
-
与
EventEmitter
不同,任何给定的listener
最多可以在每个事件type
中注册一次。尝试多次注册listener
将被忽略。¥Unlike
EventEmitter
, any givenlistener
can be registered at most once per eventtype
. Attempts to register alistener
multiple times are ignored. -
NodeEventTarget
不模拟完整的EventEmitter
API。特别是prependListener()
、prependOnceListener()
、rawListeners()
和errorMonitor
API 未被模拟。'newListener'
和'removeListener'
事件也不会触发。¥The
NodeEventTarget
does not emulate the fullEventEmitter
API. Specifically theprependListener()
,prependOnceListener()
,rawListeners()
, anderrorMonitor
APIs are not emulated. The'newListener'
and'removeListener'
events will also not be emitted. -
NodeEventTarget
没有为类型为'error'
的事件实现任何特殊的默认行为。¥The
NodeEventTarget
does not implement any special default behavior for events with type'error'
. -
NodeEventTarget
支持EventListener
对象以及作为所有事件类型句柄的函数。¥The
NodeEventTarget
supportsEventListener
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 EventTarget
s 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
#
如果设置为 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
#
-
类型:<EventTarget> 调度事件的
EventTarget
。¥Type: <EventTarget> The
EventTarget
dispatching the event.
event.target
的别名。
¥Alias for event.target
.
event.defaultPrevented
#
如果 cancelable
为 true
且 event.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.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()
#
如果 cancelable
是 true
,则将 defaultPrevented
属性设置为 true
。
¥Sets the defaultPrevented
property to true
if cancelable
is true
.
event.returnValue
#
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
#
-
类型:<EventTarget> 调度事件的
EventTarget
。¥Type: <EventTarget> The
EventTarget
dispatching the event.
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
#
-
类型:<EventTarget> 调度事件的
EventTarget
。¥Type: <EventTarget> The
EventTarget
dispatching the event.
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> Whentrue
, the listener is automatically removed when it is first invoked. Default:false
. -
passive
<boolean> 当为true
时,提示监听器不会调用Event
对象的preventDefault()
方法。默认值:false
。¥
passive
<boolean> Whentrue
, serves as a hint that the listener will not call theEvent
object'spreventDefault()
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'sabort()
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'scancelable
attribute value is false or itspreventDefault()
method was not invoked, otherwisefalse
.
将 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
<string> -
listener
<Function> | <EventListener> -
options
<Object>capture
<boolean>
从事件 type
的句柄列表中删除 listener
。
¥Removes the listener
from the list of handlers for event type
.
类:CustomEvent
#
¥Class: CustomEvent
¥Stability: 1 - Experimental.
CustomEvent
对象是 CustomEvent
网络应用接口 的改编版。实例由 Node.js 在内部创建。
¥The CustomEvent
object is an adaptation of the CustomEvent
Web API.
Instances are created internally by Node.js.
event.detail
#
¥Stability: 1 - Experimental.
只读。
¥Read-only.
类:NodeEventTarget
#
¥Class: NodeEventTarget
-
¥Extends: <EventTarget>
NodeEventTarget
是 EventTarget
的 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)
#
-
type
<string> -
listener
<Function> | <EventListener> -
返回:<EventTarget> 自身
¥Returns: <EventTarget> this
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 thetype
exist, otherwisefalse
.
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()
#
-
返回:<string[]>
¥Returns: <string[]>
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)
#
n
<number>
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])
#
-
type
<string> -
listener
<Function> | <EventListener> -
options
<Object>capture
<boolean>
-
返回:<EventTarget> 自身
¥Returns: <EventTarget> this
eventTarget.removeEventListener()
的 Node.js 特定别名。
¥Node.js-specific alias for eventTarget.removeEventListener()
.
nodeEventTarget.on(type, listener)
#
-
type
<string> -
listener
<Function> | <EventListener> -
返回:<EventTarget> 自身
¥Returns: <EventTarget> this
eventTarget.addEventListener()
的 Node.js 特定别名。
¥Node.js-specific alias for eventTarget.addEventListener()
.
nodeEventTarget.once(type, listener)
#
-
type
<string> -
listener
<Function> | <EventListener> -
返回:<EventTarget> 自身
¥Returns: <EventTarget> this
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])
#
-
type
<string> -
返回:<EventTarget> 自身
¥Returns: <EventTarget> this
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])
#
-
type
<string> -
listener
<Function> | <EventListener> -
options
<Object>capture
<boolean>
-
返回:<EventTarget> 自身
¥Returns: <EventTarget> this
Node.js 特定于 EventTarget
类的扩展,用于删除给定 type
的 listener
。removeListener()
和 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
.