EventEmitter
The publish/subscribe pattern that powers Node.js internals
Skills taught: node.eventemitter, node.events-module, node.pub-sub, node.custom-events
Creating and using EventEmitter
const { EventEmitter } = require('events');
// Create an emitter
const emitter = new EventEmitter();
// Subscribe with .on() — runs every time
emitter.on('greet', (name) => {
console.log('Hello,', name + '!');
});
// Subscribe with .once() — runs only the first time
emitter.once('connect', () => {
console.log('Connected! (will only print once)');
});
// Emit events — calls all matching listeners immediately (sync)
emitter.emit('greet', 'Alice'); // → Hello, Alice!
emitter.emit('greet', 'Bob'); // → Hello, Bob!
emitter.emit('connect'); // → Connected!
emitter.emit('connect'); // → (nothing — once() already fired)
// Check listener count
console.log('greet listeners:', emitter.listenerCount('greet')); // 1
// Remove a listener
const fn = (n) => console.log('bye', n);
emitter.on('disconnect', fn);
emitter.off('disconnect', fn); // remove it
console.log('disconnect listeners:', emitter.listenerCount('disconnect')); // 0
const { EventEmitter } = require('events');
// Extend EventEmitter to create a class with events
class FileProcessor extends EventEmitter {
async process(files) {
this.emit('start', { total: files.length });
for (let i = 0; i < files.length; i++) {
const file = files[i];
// ... processing logic ...
this.emit('progress', { file, done: i + 1, total: files.length });
}
this.emit('done', { processed: files.length });
}
}
const processor = new FileProcessor();
processor.on('start', ({ total }) => console.log(`Processing ${total} files...`));
processor.on('progress', ({ file, done, total }) => console.log(` [${done}/${total}] ${file}`));
processor.on('done', ({ processed }) => console.log(`Done! ${processed} files processed.`));
processor.on('error', (err) => console.error('Error:', err.message));
processor.process(['report.csv', 'users.json', 'orders.xlsx']);
Tip: Always add an `.on('error', handler)` listener to EventEmitter instances you don't fully control. An unhandled 'error' event crashes the Node.js process.
Frequently Asked Questions
How does EventEmitter relate to Node.js streams?
Streams (Readable, Writable, Transform) extend EventEmitter. A Readable stream emits 'data' events for each chunk, 'end' when done, and 'error' on failure. A Writable emits 'drain' when its buffer is empty. Everything you learned about EventEmitter applies directly to working with streams — they're the same mechanism.