Events Module
Imagine a classroom where students raise their hands when they have a question. The teacher doesn't constantly check each student – instead, the teacher waits for the "hand raise" event and then responds. This is exactly how the **Events module** works in Node.js!
What is the Events Module?
The Events module provides a way to handle asynchronous events. Many objects in Node.js emit events – for example, a server emits a 'request' event when a client connects, a stream emits a 'data' event when data is available. The Events module lets you create, emit, and listen for your own custom events.
Think of EventEmitter as a notification system. You can subscribe to events you care about, and when those events happen, you get notified.
The EventEmitter Class
The core of the Events module is the `EventEmitter` class.
const EventEmitter = require('events');const myEmitter = new EventEmitter();Listening to Events (on)
Use the `on()` method to register a listener for an event.
<!-- Listen for 'greet' event -->myEmitter.on('greet', (name) => { console.log(`Hello, ${name}!`);});
myEmitter.on('greet', (name) => { console.log(`Welcome to Node.js, ${name}!`);});Emitting Events (emit)
Trigger an event with the `emit()` method.
myEmitter.emit('greet', 'Alice');<!-- Output: --><!-- Hello, Alice! --><!-- Welcome to Node.js, Alice! -->Listening Once (once)
Sometimes you want to listen to an event only once.
myEmitter.once('initialize', () => { console.log('Initialized once!');});
myEmitter.emit('initialize'); <!-- Prints -->myEmitter.emit('initialize'); <!-- Does nothing (listener removed) -->Removing Listeners
You can remove specific listeners or all listeners.
const callback = () => console.log('Event fired!');
myEmitter.on('test', callback);
<!-- Remove specific listener -->myEmitter.off('test', callback);<!-- Or remove all listeners for an event -->myEmitter.removeAllListeners('test');Getting Listener Information
myEmitter.on('event1', () => {});myEmitter.on('event1', () => {});
console.log(myEmitter.listenerCount('event1')); <!-- 2 -->console.log(myEmitter.eventNames()); <!-- ['event1'] -->Error Events
If an EventEmitter emits an 'error' event and no one is listening, Node.js will throw an exception and crash. Always listen for errors!
myEmitter.on('error', (err) => { console.error('An error occurred:', err.message);});
myEmitter.emit('error', new Error('Something went wrong'));Creating Your Own EventEmitter Class
You can create custom classes that inherit from EventEmitter.
const EventEmitter = require('events');
class MyTimer extends EventEmitter { constructor(interval) { super(); this.interval = interval; this.count = 0; } start() { const timer = setInterval(() => { this.count++; this.emit('tick', this.count); if (this.count === 5) { clearInterval(timer); this.emit('done'); } }, this.interval); }}
<!-- Use the custom class -->const timer = new MyTimer(1000);
timer.on('tick', (count) => { console.log(`Tick #${count}`);});
timer.on('done', () => { console.log('Timer done!');});
timer.start();Real-World Example: HTTP Server Events
Many Node.js core modules use events. Here's how an HTTP server uses events:
const http = require('http');
const server = http.createServer();
<!-- Listen for 'request' events -->server.on('request', (req, res) => { res.end('Hello World');});
server.on('listening', () => { console.log('Server is listening');});
server.listen(3000);Two Minute Drill
- EventEmitter is the core of Node.js asynchronous event handling.
- Use `on()` to listen for events, `emit()` to trigger them.
- `once()` listens for an event only one time.
- Always handle 'error' events to prevent crashes.
- You can create your own classes that extend EventEmitter.
- Many Node.js core modules (http, streams, fs) use events internally.
Need more clarification?
Drop us an email at career@quipoinfotech.com
