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