EventEmitter
- Node.js course
- Intermediate
- Lesson 1/116
- 5 min
Learn event management with EventEmitter.
What is EventEmitter?
In Node.js an EventEmitter is a class that emits events. It is imported from the events module: const { EventEmitter } = require("events");. An instance is created with new EventEmitter().
An event is a named signal. A publisher emits an event (emit) and listeners listen for it (on). Multiple listeners can watch the same event. Node.js http and stream APIs are built on this structure, so understanding EventEmitter means understanding the heart of Node.js.
The event concept
An EventEmitter uses two core methods. on(eventName, listener) registers a listener; emit(eventName, ...args) calls the registered listeners. The event name is a free-form string; common examples are "data", "end", "error".
A listener is the function that runs when the event is emitted. Arguments pass from emit to the listener in order. If no listener is registered, emit passes silently; it does not throw. This enables loosely coupled design: the publisher does not need to know the listeners.
Practice Create an EventEmitter instance
Import EventEmitter from the events module. Create an instance named emitter and print "Emitter ready" with console.log.
Starter code
// Import EventEmitter
// write here
// Create an emitter instance
// write here
// Print the ready message
// write hereSample solution
const { EventEmitter } = require("events");
const emitter = new EventEmitter();
console.log("Emitter ready");Expected output
Yayıncı hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is EventEmitter imported?
const { EventEmitter } = require("events");- const { EventEmitter } = require("events") Correct answer
- import { EventEmitter } from "node"
- const emitter = require("events")
- const EventEmitter = new events()
Explanation: EventEmitter is imported with destructuring from the events module.
2 Complete the module name
const { EventEmitter } = require("____");
const { EventEmitter } = require("events");
Explanation: The built-in module is named events.
3 Match each piece to its role
| Term | Meaning |
|---|---|
EventEmitter |
Event emitter class |
events |
Built-in module |
new |
Creates an instance |
emit |
Fires an event |