bhylu.com

Advertisements

Node.js EventEmitter

EventEmitter lets an object announce named events. Listeners are synchronous calls during emit unless the listener itself starts asynchronous work.

How it works

Use a stable function reference when you must remove a listener later. once removes itself after its first event, while on remains until explicitly removed. The error event has special behaviour when nobody handles it, so wire a deliberate error path before an emitter can fail. This original desk fixture counts checked-out units and then tears down its listener, demonstrating ownership instead of adding a fresh listener on every request.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as event-emitter.mjs in a separate empty exercises folder and run node event-emitter.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

event-emitter.mjs

import { EventEmitter } from 'node:events';
const desk = new EventEmitter();
let total = 0;
const count = (units) => {
  total += units;
};
desk.on('checkout', count);
desk.once('ready', () => console.log('Desk ready'));
desk.emit('ready');
desk.emit('ready');
desk.emit('checkout', 2);
desk.off('checkout', count);
desk.emit('checkout', 9);
console.log(total, desk.listenerCount('checkout'));

Expected result

Desk ready
2 0

The one-time announcement appears once and the removed checkout listener no longer changes the total. In an application, the owner that registers a listener should usually also define when it is removed.

Use the Node.js API reference for the precise version contract.