Node.js Events
Many Node objects are event emitters: they announce things with emit, and you react with on.
ExampleNode.js
const EventEmitter = require("events");
class Chat extends EventEmitter {}
const chat = new Chat();
chat.on("message", (user, text) => console.log(`${user}: ${text}`));
chat.on("message", (user) => console.log(`(logged a message from ${user})`));
chat.once("join", (user) => console.log(`${user} joined`));
chat.emit("join", "Ada");
chat.emit("join", "Sam"); // once: no output
chat.emit("message", "Ada", "Hello!");
console.log(chat.listenerCount("message"));Output
Ada joined Ada: Hello! (logged a message from Ada) 2
Quick check
Which method triggers an event?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.