events module
The events module is a core Node.js module that implements the observer pattern through the EventEmitter class. This module is the foundation of Node.js event-driven architecture—HTTP servers, streams, and the filesystem module all build on it. You can emit custom events and register listeners to respond to those events, enabling loose coupling between parts of your application.
Syntax
const EventEmitter = require('events'); // CommonJS
import { EventEmitter } from 'events'; // ESM
In CommonJS, the events module is globally available—you don’t need to install it. For ESM, import the EventEmitter class directly.
EventEmitter Class
The EventEmitter is the core class. It allows you to register listener functions that are called when a specific event is emitted.
Creating an EventEmitter
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const emitter = new MyEmitter();
emitter.on(eventName, listener)
Registers a listener function for the specified event. The listener is called every time the event is emitted.
| Parameter | Type | Default | Description |
|---|---|---|---|
eventName | string or symbol | — | The name of the event |
listener | function | — | The callback function (...args) => {} |
Returns: EventEmitter — The emitter for chaining
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', (name) => {
console.log('Hello, ' + name);
});
emitter.emit('greet', 'Alice');
Output:
Hello, Alice
emitter.once(eventName, listener)
Registers a listener that is called at most once. After the first emission, the listener is removed automatically.
| Parameter | Type | Default | Description |
|---|---|---|---|
eventName | string or symbol | — | The name of the event |
listener | function | — | The callback function |
Returns: EventEmitter
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.once('init', () => {
console.log('Initialization complete');
});
emitter.emit('init');
emitter.emit('init'); // This emission is ignored
Output:
Initialization complete
emitter.emit(eventName[, …args])
Synchronously calls each listener registered for the event, passing the provided arguments.
| Parameter | Type | Default | Description |
|---|---|---|---|
eventName | string or symbol | — | The name of the event |
...args | any | — | Arguments passed to listeners |
Returns: boolean — true if the event had listeners, false otherwise
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('data', (chunk) => {
console.log('Received:', chunk);
});
const result = emitter.emit('data', 'Hello World');
console.log('Event had listeners:', result);
const noListeners = emitter.emit('nonexistent');
console.log('Nonexistent event:', noListeners);
Output:
Received: Hello World
Event had listeners: true
Nonexistent event: false
emitter.off(eventName, listener)
Removes a specific listener from the event. Use this to clean up handlers you no longer need.
| Parameter | Type | Default | Description |
|---|---|---|---|
eventName | string or symbol | — | The event name |
listener | function | — | The listener function to remove |
Returns: EventEmitter
const EventEmitter = require('events');
const emitter = new EventEmitter();
function handler(msg) {
console.log('Handler 1:', msg);
}
emitter.on('message', handler);
emitter.emit('message', 'First');
emitter.off('message', handler);
emitter.emit('message', 'Second');
Output:
First
emitter.removeListener(eventName, listener)
Alias for emitter.off(). Both methods do the same thing.
emitter.removeAllListeners([eventName])
Removes all listeners, or all listeners for a specified event. Use with caution—this breaks all registered handlers.
| Parameter | Type | Default | Description |
|---|---|---|---|
eventName | string | optional | If omitted, removes all listeners from all events |
Returns: EventEmitter
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('a', () => console.log('a'));
emitter.on('b', () => console.log('b'));
emitter.on('c', () => console.log('c'));
console.log('Before removeAllListeners:', emitter.listenerCount('a'));
emitter.removeAllListeners('a');
console.log('After removing a:', emitter.listenerCount('a'));
console.log('b still exists:', emitter.listenerCount('b'));
Output:
Before removeAllListeners: 1
After removing a: 0
b still exists: 1
emitter.listenerCount(eventName)
Returns the number of listeners registered for a given event.
| Parameter | Type | Default | Description |
|---|---|---|---|
eventName | string | — | The event to count |
Returns: number
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('data', () => {});
emitter.on('data', () => {});
emitter.on('data', () => {});
console.log('Listener count:', emitter.listenerCount('data'));
Output:
Listener count: 3
emitter.getMaxListeners()
Returns the current maximum listener number. The default is 10. You can change this with setMaxListeners().
Returns: number
const EventEmitter = require('events');
const emitter = new EventEmitter();
console.log('Default max listeners:', emitter.getMaxListeners());
Output:
Default max listeners: 10
emitter.setMaxListeners(n)
Sets the maximum number of listeners. When more listeners are added than the limit, Node.js emits a warning to help detect memory leaks.
| Parameter | Type | Default | Description |
|---|---|---|---|
n | number | — | Maximum number of listeners |
Returns: EventEmitter
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.setMaxListeners(20);
console.log('New max:', emitter.getMaxListeners());
Output:
New max: 20
emitter.eventNames()
Returns an array of all registered event names.
Returns: Array<string | symbol>
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('open', () => {});
emitter.on('close', () => {});
emitter.on('error', () => {});
console.log('Event names:', emitter.eventNames());
Output:
Event names: [ 'open', 'close', 'error' ]
emitter.listeners(eventName)
Returns a copy of the array of listeners for the specified event.
| Parameter | Type | Default | Description |
|---|---|---|---|
eventName | string | — | The event name |
Returns: function[Global_Objects::eval]
Error Events
When an error occurs within an EventEmitter, it emits an 'error' event. If no listener is registered for 'error', Node.js throws the error and may crash the process. Always handle error events in production code.
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('error', (err) => {
console.error('Error occurred:', err.message);
});
emitter.emit('error', new Error('Something went wrong'));
Output:
Error occurred: Something went wrong
Common Patterns
Inheriting from EventEmitter
Create custom classes that emit events:
const EventEmitter = require('events');
class FileWatcher extends EventEmitter {
constructor(filename) {
super();
this.filename = filename;
}
watch() {
console.log('Watching ' + this.filename);
setTimeout(() => {
this.emit('change', { timestamp: Date.now() });
}, 1000);
}
}
const watcher = new FileWatcher('config.json');
watcher.on('change', (data) => {
console.log('File changed at ' + data.timestamp);
});
watcher.watch();
Output:
Watching config.json
File changed at 1709512345678
Using with EventEmitter.defaultMaxListeners
Change the default limit for all new emitters:
const { EventEmitter, defaultMaxListeners } = require('events');
console.log('Default maxListeners:', defaultMaxListeners);
// Increase global default
EventEmitter.defaultMaxListeners = 15;