Node.js v18.12.1 documentation


Table of contents

Events事件#

Stability: 2 - Stable

Source Code: lib/events.js

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.Node.js核心API的大部分是围绕一个惯用的异步事件驱动架构构建的,在该架构中,某些类型的对象(称为“发射器”)会发出导致调用Function对象(“侦听器”)的命名事件。

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.例如:net.Server对象在每次对等体连接到它时发出一个事件;fs.ReadStream在文件打开时发出事件;每当数据可供读取时,就会发出一个事件。

All objects that emit events are instances of the EventEmitter class. 所有发出事件的对象都是EventEmitter类的实例。These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. 这些对象公开了一个eventEmitter.on()函数,该函数允许一个或多个函数附加到对象发出的命名事件。Typically, event names are camel-cased strings but any valid JavaScript property key can be used.通常,事件名称是骆驼大小写的字符串,但可以使用任何有效的JavaScript属性键。

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. EventEmitter对象发出事件时,将同步调用附加到该特定事件的所有函数。Any values returned by the called listeners are ignored and discarded.被调用侦听器返回的任何值都将被忽略并丢弃。

The following example shows a simple EventEmitter instance with a single listener. 下面的示例显示了一个具有单个侦听器的简单EventEmitter实例。The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event.eventEmitter.on()方法用于注册侦听器,而eventEmitter.emit()方法则用于触发事件。

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');