events

import { EventEmitter } from "node:events";

const bus = new EventEmitter();
let seen = null;
bus.on("hit", (value) => { seen = value; });
bus.emit("hit", 42);

Output:

42

on and once

on keeps listening once removes itself after the first event Use once for startup and handshake events

The leak

Adding a listener inside a request and never removing it keeps the closure alive After enough requests the process slows down and nobody can say why

const handler = (value) => handle(value);
bus.on("hit", handler);
bus.off("hit", handler);

Keep the function reference so you can remove it

Error events

An error event with no listener throws That is deliberate A swallowed error is worse than a loud crash

Next

Serving requests in 07 http

Posted