What is an event in the context of Node.js?
1. What an event is in Node.js
An event is a signal that something happened (for example, data arrived, a file read finished, a client connected, and so on).
Node.js is built around an event-driven architecture, where code reacts to events, rather than blocking while waiting for them to finish.
2. The events mechanism: EventEmitter
At its core is the EventEmitter class from the events module.
It lets objects:
- emit events (
emit); - listen for events (
on).
Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Subscribe to an event
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
// Emit the event
emitter.emit('greet', 'Tim');Here:
'greet'is the event name,onis the listener,emitfires the event,- the callback passed to
.on()gets called.
3. How this ties into I/O
Node.js uses events for every asynchronous operation:
- network requests (
http,net), - the filesystem (
fs), - streams,
- timers (
setTimeout,setInterval).
For example:
const fs = require('fs');
const stream = fs.createReadStream('file.txt');
stream.on('data', chunk => console.log('Got a chunk'));
stream.on('end', () => console.log('File read'));Here:
- the stream emits events (
data,end,error), - and you react to them, instead of waiting for synchronous completion.
4. The Event Loop's role
Every event is processed through the Event Loop, the "engine" that:
- watches the event queue;
- calls registered callbacks when an event happens;
- never blocks (everything is non-blocking).
An example lifecycle:
[Incoming data] → an event fires → callback → processing → the next cycle5. Where events show up
| Object | Typical events |
|---|---|
fs.ReadStream | data, end, error, close |
http.Server | request, connection, close |
net.Socket | connect, data, end, error |
process | exit, uncaughtException, SIGINT |
EventEmitter | any custom ones ('ready', 'updated', and so on) |
6. Why the event model is efficient
- Asynchrony with no blocking: the thread doesn't wait, events fire once the result is ready.
- High scalability: thousands of connections can be served on one thread.
- Simple reaction logic: instead of a wait loop, subscribing to events.
Summary
An event in Node.js is a notification that a specific action occurred.
It's handled through the EventEmitter mechanism, and its execution is driven by the Event Loop.
All of Node.js's asynchrony, file operations, HTTP, streams, timers, is built on the event model, where code reacts to events instead of waiting for them to finish.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.