How to Listen for Events in Node.js: Simple Guide
In Node.js, you listen for events by using the
EventEmitter class from the events module. You create an emitter object and attach a listener function with on(eventName, listener) to respond when the event occurs.Syntax
To listen for an event in Node.js, you first import the EventEmitter class, create an instance, then use on(eventName, listener) to register a function that runs when the event fires.
eventName: The name of the event to listen for (string).listener: The function called when the event happens.
javascript
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('eventName', () => { // code to run when eventName is emitted });
Example
This example shows how to listen for a custom event called greet. When the event is emitted, the listener prints a greeting message.
javascript
const EventEmitter = require('events'); const emitter = new EventEmitter(); // Listen for 'greet' event emitter.on('greet', (name) => { console.log(`Hello, ${name}!`); }); // Emit 'greet' event with a name emitter.emit('greet', 'Alice');
Output
Hello, Alice!
Common Pitfalls
Common mistakes include:
- Not creating an
EventEmitterinstance before listening. - Using
emitbefore attaching listeners, so the event is missed. - Forgetting to pass the correct event name string.
- Not handling asynchronous listeners properly.
Always attach listeners before emitting events to ensure they catch the event.
javascript
const EventEmitter = require('events'); const emitter = new EventEmitter(); // Wrong: emitting before listener emitter.emit('start'); emitter.on('start', () => { console.log('Started'); }); // Right: listener before emitting emitter.on('start', () => { console.log('Started'); }); emitter.emit('start');
Output
Started
Quick Reference
| Method | Description |
|---|---|
| on(event, listener) | Add a listener for the event |
| once(event, listener) | Add a listener that runs once |
| emit(event, ...args) | Trigger the event with arguments |
| removeListener(event, listener) | Remove a specific listener |
Key Takeaways
Use EventEmitter and its on() method to listen for events in Node.js.
Always attach listeners before emitting events to avoid missing them.
Event names are strings and must match exactly when emitting and listening.
You can pass data to listeners by including arguments in emit().
Use once() for listeners that should run only one time.