emitter.on()

Registers a listener that runs every time the named event is emitted.

Since Node 0.x Spec ↗

Syntax

emitter.on(eventName, listener)

Parameters

NameTypeRequiredDescription
eventName string | symbol Yes The name of the event to listen for.
listener function Yes The callback invoked with the emitted arguments.

Returns

EventEmitter — The emitter, for chaining.

Examples

import { EventEmitter } from 'node:events';

const bus = new EventEmitter();
bus.on('msg', (text) => console.log('got', text));
bus.emit('msg', 'hello');
bus.emit('msg', 'again');
Output
got hello
got again
import { createServer } from 'node:http';

const server = createServer();
server.on('request', (req, res) => res.end('ok'));
server.on('error', (e) => console.error(e.code));
server.listen(3000);

Notes

Listeners fire synchronously in registration order. `on` keeps listening until removed with `off`/`removeListener`; forgetting to remove listeners on long-lived emitters causes memory leaks. Use `once` for one-shot events.

See also