`EventEmitter` is the base class behind streams, servers, and many other Node objects. You register listeners with `.on(event, handler)` and fire them with `.emit(event, ...args)`.
js
import { EventEmitter } from "node:events";
class Wallet extends EventEmitter {
deposit(amount) {
this.balance = (this.balance ?? 0) + amount;
this.emit("deposit", amount, this.balance);
}
}
const w = new Wallet();
w.on("deposit", (amount, balance) => console.log(`+${amount}, now ${balance}`));
w.deposit(10);By convention, an `"error"` event with no listener attached throws and crashes the process — always attach an `"error"` handler on emitters that might fail, such as sockets and streams.