Skip to main content

Events

Stability: 2 - Stable
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. 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. 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.
import { EventEmitter } from 'node:events';

class MyEmitter extends EventEmitter {}

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

Passing Arguments and this to Listeners

The eventEmitter.emit() method allows an arbitrary set of arguments to be passed to the listener functions. 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.
const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
  console.log(a, b, this, this === myEmitter);
  // Prints:
  //   a b MyEmitter {...} true
});
myEmitter.emit('event', 'a', 'b');
It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the this keyword will no longer reference the EventEmitter instance:
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  console.log(a, b, this);
  // Prints: a b undefined
});
myEmitter.emit('event', 'a', 'b');

Asynchronous vs. Synchronous

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 setImmediate() or process.nextTick():
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('this happens asynchronously');
  });
});
myEmitter.emit('event', 'a', 'b');

Handling Events Only Once

When a listener is registered using the eventEmitter.on() method, that listener is invoked every time the named event is emitted.
let m = 0;
myEmitter.on('event', () => {
  console.log(++m);
});
myEmitter.emit('event'); // Prints: 1
myEmitter.emit('event'); // Prints: 2
Using the eventEmitter.once() method, it is possible to register a listener that is called at most once for a particular event:
let m = 0;
myEmitter.once('event', () => {
  console.log(++m);
});
myEmitter.emit('event'); // Prints: 1
myEmitter.emit('event'); // Ignored

Error Events

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. 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.
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js
As a best practice, listeners should always be added for the ‘error’ events:
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

Class: EventEmitter

The EventEmitter class is defined and exposed by the node:events module.
import { EventEmitter } from 'node:events';
// or
const EventEmitter = require('node:events');
All EventEmitters emit the event ‘newListener’ when new listeners are added and ‘removeListener’ when existing listeners are removed.

new EventEmitter([options])

options
Object

Event: ‘newListener’

Added in: v0.1.26
eventName
string | symbol
required
The name of the event being listened for
listener
Function
required
The event handler function
The EventEmitter instance will emit its own ‘newListener’ event before a listener is added to its internal array of listeners.
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

Event: ‘removeListener’

Added in: v0.9.3
eventName
string | symbol
required
The event name
listener
Function
required
The event handler function
The ‘removeListener’ event is emitted after the listener is removed.

emitter.addListener(eventName, listener)

Added in: v0.1.26
eventName
string | symbol
required
The name of the event
listener
Function
required
The callback function
Alias for emitter.on(eventName, listener).

emitter.emit(eventName[, …args])

Added in: v0.1.26
eventName
string | symbol
required
The name of the event
...args
any
Arguments to pass to the listeners
return
boolean
Returns true if the event had listeners, false otherwise.
Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();

myEmitter.on('event', (a, b) => {
  console.log(a, b);
});

myEmitter.emit('event', 'a', 'b');
// Prints: a b

emitter.eventNames()

Added in: v6.0.0
return
Array
Returns an array listing the events for which the emitter has registered listeners.
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()

Added in: v1.0.0
return
integer
Returns the current max listener value for the EventEmitter.
Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.

emitter.listenerCount(eventName[, listener])

Added in: v3.2.0
eventName
string | symbol
required
The name of the event being listened for
listener
Function
The event handler function
return
integer
Returns the number of listeners listening for the event named eventName.
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(myEmitter.listenerCount('event'));
// Prints: 2

emitter.listeners(eventName)

Added in: v0.1.26
eventName
string | symbol
required
The name of the event
return
Function[]
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)

Added in: v10.0.0
eventName
string | symbol
required
The name of the event
listener
Function
required
The callback function
Alias for emitter.removeListener().

emitter.on(eventName, listener)

Added in: v0.1.101
eventName
string | symbol
required
The name of the event
listener
Function
required
The callback function
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!');
});
Returns a reference to the EventEmitter, so that calls can be chained.

emitter.once(eventName, listener)

Added in: v0.3.0
eventName
string | symbol
required
The name of the event
listener
Function
required
The callback function
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!');
});
Returns a reference to the EventEmitter, so that calls can be chained.

emitter.prependListener(eventName, listener)

Added in: v6.0.0
eventName
string | symbol
required
The name of the event
listener
Function
required
The callback function
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.
server.prependListener('connection', (stream) => {
  console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.

emitter.prependOnceListener(eventName, listener)

Added in: v6.0.0
eventName
string | symbol
required
The name of the event
listener
Function
required
The callback function
Adds a one-time listener function for the event named eventName to the beginning of the listeners array.

emitter.removeAllListeners([eventName])

Added in: v0.1.26
eventName
string | symbol
The name of the event
Removes all listeners, or those of the specified eventName. Returns a reference to the EventEmitter, so that calls can be chained.

emitter.removeListener(eventName, listener)

Added in: v0.1.26
eventName
string | symbol
required
The name of the event
listener
Function
required
The callback function
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);

emitter.setMaxListeners(n)

Added in: v0.3.5
n
integer
required
The new maximum number of listeners
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. Returns a reference to the EventEmitter, so that calls can be chained.

emitter.rawListeners(eventName)

Added in: v9.4.0
eventName
string | symbol
required
The name of the event
return
Function[]
Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

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

Added in: v11.13.0, v10.16.0
emitter
EventEmitter
required
The event emitter
name
string
required
The name of the event being listened for
options
Object
Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits ‘error’ while waiting.
import { once, EventEmitter } from 'node:events';

const ee = new EventEmitter();

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

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

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

Added in: v13.6.0, v12.16.0
emitter
EventEmitter
required
The event emitter
eventName
string
required
The name of the event being listened for
options
Object
return
AsyncIterator
Returns an AsyncIterator that iterates eventName events emitted by the emitter.
import { on, EventEmitter } from 'node:events';

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')) {
  console.log(event);
}
// Prints:
//   ['bar']
//   [42]

EventEmitter.defaultMaxListeners

defaultMaxListeners
integer
default:"10"
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 EventEmitter.defaultMaxListeners property can be used.
import { EventEmitter } from 'node:events';

EventEmitter.defaultMaxListeners = 20;