on and emit
- Node.js course
- Intermediate
- Lesson 2/116
- 5 min
Learn to listen with .on and emit events with .emit.
on and emit
The on method registers a listener. Signature: emitter.on(eventName, listener). The emit method fires the event and calls listeners: emitter.emit(eventName, ...args).
Example: emitter.on("hello", (name) => console.log("Hi " + name)); adds a listener. The call emitter.emit("hello", "Alex") prints Hi Alex. The second and later parameters of emit pass to the listener as arguments. The event name must match on both sides.
Multiple listeners
If you call on multiple times for the same event, each listener is called in order. emit returns true if at least one listener exists, false otherwise.
Arguments can be as many as you like: emitter.emit("sale", product, qty, price). The listener receives them as (product, qty, price) => {...}. Extra arguments are silently ignored; missing ones become undefined. This flexibility makes EventEmitter practical for daily workflows.
Practice Emit and listen for an event
Create an emitter instance. Listen for the "greeting" event: the listener takes (name) and prints "Hello " + name. Then fire the event with emitter.emit("greeting", "Alex").
Starter code
// Create an emitter instance
// write here
// Listen for the "greeting" event
// write here
// Fire the event
// write hereSample solution
const { EventEmitter } = require("events");
const emitter = new EventEmitter();
emitter.on("greeting", (name) => console.log("Hello " + name));
emitter.emit("greeting", "Alex");Expected output
Merhaba Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the listening line
emitter.____("greeting", () => { console.log("Merhaba"); });
emitter.on("greeting", () => { console.log("Merhaba"); });
Explanation: The on method registers a listener.
2 What does emitter.emit("greeting", "Ayşe") do?
emitter.emit("greeting", "Ayşe")- Yeni bir "greeting" dinleyicisi ekler
- Calls the "greeting" listeners and passes the argument "Ayşe" Correct answer
- Deletes the "greeting" event
- Only returns the event name
Explanation: emit calls the listeners and passes the argument.
3 Match each method to its role
| Term | Meaning |
|---|---|
on |
Registers a listener |
emit |
Fires the event |
event name |
Name of the signal |
argument |
Value passed to the listener |