0
0
Node.jsframework~5 mins

Once listeners in Node.js

Choose your learning style9 modes available
Introduction
Once listeners let you run a function only one time when an event happens. This helps avoid running the same code many times by mistake.
You want to handle a user login event only the first time it happens.
You want to load some data once when a server starts.
You want to clean up resources only once after a task finishes.
You want to listen for a connection event just the first time a client connects.
Syntax
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.once('eventName', listenerFunction);
The listenerFunction runs only once for the first 'eventName' event.
After running once, the listener is automatically removed.
Examples
The message 'Hello once!' prints only once even though we emit 'greet' twice.
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.once('greet', () => {
  console.log('Hello once!');
});

emitter.emit('greet');
emitter.emit('greet');
The 'onConnect' function runs only the first time the 'connect' event happens.
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();

function onConnect() {
  console.log('Client connected once');
}

emitter.once('connect', onConnect);

emitter.emit('connect');
emitter.emit('connect');
Sample Program
This program creates a Server class that emits a 'start' event. The listener runs only once even though the event is emitted twice.
Node.js
const EventEmitter = require('events');

class Server extends EventEmitter {
  start() {
    console.log('Server starting...');
    this.emit('start');
  }
}

const server = new Server();

// Listen once for the 'start' event
server.once('start', () => {
  console.log('Server has started - this runs only once');
});

// Emit 'start' event twice
server.start();
server.start();
OutputSuccess
Important Notes
Time complexity: Adding a once listener is O(1), running it is O(1).
Space complexity: Uses memory for one listener until it runs.
Common mistake: Expecting the listener to run multiple times when it only runs once.
Use once listeners when you want to react only to the first occurrence of an event, unlike regular listeners that run every time.
Summary
Once listeners run their function only the first time an event happens.
They automatically remove themselves after running once.
Use them to handle events that should trigger only a single time.