Sikau

Node.js · Day 5 · about 25 min

Events

EventEmitter: the pattern behind servers and streams.

Tell me when it happens

Servers emit request, streams emit data and end, processes emit exit. They're all built on one class: EventEmitter — objects that announce things, and listeners that react.

on, once, emit

import { EventEmitter } from "node:events";

class Kitchen extends EventEmitter {
  order(dish) {
    this.emit("order", dish);
    setTimeout(() => this.emit("ready", dish), 50);
  }
}

const kitchen = new Kitchen();
kitchen.on("order", (dish) => console.log("Cooking", dish));
kitchen.on("ready", (dish) => console.log(dish, "is ready!"));
kitchen.once("ready", () => console.log("(first dish out)"));

kitchen.order("Momo");
kitchen.order("Thukpa");
  • Emit an error event with no listener and Node throws — always handle error on emitters.
  • emitter.off(name, fn) removes a listener; forgetting to is a classic memory leak.
  • Streams (fs.createReadStream, HTTP requests) are EventEmitters that deliver data in chunks.

The rest of this lesson

  • When to use eventsexplain
  • Streams are events tooexplain
  • How many logs?predict
  • on vs oncepredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js