0
0
NodejsHow-ToBeginner · 3 min read

How to Use once for Event in Node.js: Simple Guide

In Node.js, use the once method on an EventEmitter to listen for an event only once. It automatically removes the listener after the event fires the first time, preventing multiple triggers.
📐

Syntax

The once method is called on an EventEmitter instance with two arguments:

  • eventName: The name of the event to listen for.
  • listener: The callback function to run when the event occurs.

After the event fires once, the listener is removed automatically.

javascript
emitter.once(eventName, listener);
💻

Example

This example shows how to use once to listen for a 'message' event only once. The listener runs the first time the event is emitted, then it stops listening.

javascript
import { EventEmitter } from 'events';

const emitter = new EventEmitter();

emitter.once('message', (text) => {
  console.log('Received message:', text);
});

emitter.emit('message', 'Hello!');
emitter.emit('message', 'This will not be logged.');
Output
Received message: Hello!
⚠️

Common Pitfalls

One common mistake is using on instead of once when you want the listener to run only once. This causes the listener to run every time the event fires, which can lead to unexpected behavior or memory leaks.

Another pitfall is forgetting that once removes the listener automatically, so if you need to listen again, you must add the listener again.

javascript
import { EventEmitter } from 'events';

const emitter = new EventEmitter();

// Wrong: listener runs multiple times
emitter.on('data', () => {
  console.log('Data received');
});

emitter.emit('data');
emitter.emit('data');

// Right: listener runs only once
emitter.once('data', () => {
  console.log('Data received once');
});

emitter.emit('data');
emitter.emit('data');
Output
Data received Data received Data received once
📊

Quick Reference

Use once when you want to handle an event a single time and then stop listening. It helps avoid memory leaks and repeated handling.

  • Use: emitter.once(eventName, listener)
  • Removes listener: Automatically after first event
  • Alternative: emitter.on(eventName, listener) for multiple events

Key Takeaways

Use once to listen to an event only one time in Node.js.
once automatically removes the listener after the first event fires.
Avoid using on if you want the listener to run just once.
If you need to listen again after the first event, add the listener again.
Using once helps prevent memory leaks from unused listeners.