Node.js Events

The EventEmitter pattern.

✍️ 2 exercises in this lesson

Much of Node is event-driven. The EventEmitter class lets objects emit named events that listeners react to.

  • emitter.on("event", listener): listen.
  • emitter.once("event", listener): listen once.
  • emitter.emit("event", data): trigger.

Servers, streams and sockets are all EventEmitters.

Key Takeaways: Node.js Events

Mastering Node.js Events helps you write clean and reliable Node.js code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Node.js Events Code Example

Node.js
import { EventEmitter } from "node:events";

class Shop extends EventEmitter {
  order(item) {
    console.log("Order placed:", item);
    this.emit("ordered", item);
  }
}

const shop = new Shop();
shop.on("ordered", item => console.log("📧 Email sent for", item));
shop.on("ordered", item => console.log("📦 Packing", item));

shop.order("Laptop");
Output
Order placed: Laptop
📧 Email sent for Laptop
📦 Packing Laptop
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Node.js Events Practice Exercises

Check what you learned in “Node.js Events”.

/ 2 solved
Fill in the blank

Trigger an event.

shop.("ordered", item);
✓ Correct! Not quite. Try again.
Multiple choice

Which class lets objects emit named events?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services