Node’s core APIs are event-driven
Most Node.js I/O objects extend EventEmitter and signal progress and completion
by emitting named events. Knowing each event name, which object emits it, and the
listener’s arguments is essential to wiring up servers, streams and processes.
This reference lists the core built-in events by module.
How it works
You react to an event by registering a listener with the documented signature. The emitter calls every listener synchronously, in order, with the event’s payload arguments:
server.on("request", (req, res) => res.end("ok"));
readable.on("data", (chunk) => total += chunk.length);
readable.on("end", () => console.log("done"));
readable.on("error", (err) => console.error(err)); // always attach
child.on("exit", (code, signal) => console.log(code, signal));
Use on for repeated events and once for one-shot events. The error event is
special: an unhandled error throws and crashes the process.
Tips and notes
- Always attach an
errorlistener to every stream, socket and server before use. datais emitted only in flowing mode — calling.on("data")switches a readable stream into flowing mode.- For child processes, wait for
close(not justexit) when you must be sure all stdout/stderr has been flushed. processevents likeuncaughtException,unhandledRejection,SIGINTandbeforeExitlet you implement graceful shutdown.- Removing listeners with
removeListener/offprevents leaks on long-lived emitters; watch for theMaxListenersExceededWarning.