Events & the Event Loop
How Node stays fast: the event loop and the EventEmitter pattern that powers everything.
What you will learn
- Understand the event loop at a high level
- Use the EventEmitter
- Connect this to async behaviour
Why Node is non-blocking
Node uses a single event loop that handles many operations without waiting. When a slow task (a file read, a database query) finishes, Node fires an event and runs your callback. This is why Node handles thousands of connections efficiently.
EventEmitter
Much of Node is built on events: one part of your code announces that something happened, and other parts that were listening react to it. It is like a doorbell — pressing it (emitting) makes anyone who is listening come to the door. You create this pattern yourself with the built-in events module.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("greet", (name) => {
console.log("Hello,", name);
});
emitter.emit("greet", "Asha"); // logs: Hello, AshaNote: Output:
Hello, Asha
Step by step: new EventEmitter() makes an object that can send and receive events. emitter.on("greet", ...) listens for an event named "greet" and says what to do when it happens. emitter.emit("greet", "Asha") fires that event and passes "Asha" along — which arrives as the name in the listener, so it prints Hello, Asha. If nothing were listening for "greet", emitting it would simply do nothing.
Tip: Servers, streams and many Node objects are EventEmitters — when you write server.on("request", ...) you are using this exact pattern.
Q. What lets Node handle many operations without waiting around?
✍️ Practice
- Create an
EventEmitter, listen for a custom event, and emit it with data. - Add two listeners for the same event.
🏠 Homework
- Read about the event loop and write a 3-sentence summary in your own words.