what is on and once in node
What is "on" and "once" in Node.js?
In Node.js, events are at the core of its asynchronous, event-driven architecture. They allow certain parts of your code to listen for specific events and then respond accordingly. Two commonly used event listeners in Node.js are "on" and "once".
The "on" Listener
The "on" listener is used to attach an event handler function for one or more events. It listens for the specified event and triggers the attached function each time the event is emitted. This function can take arguments passed by the event emitter, providing useful information to the developer.
The syntax of the "on" listener is as follows:
emitter.on(eventName, listener)
- eventName: The name of the event to listen for.
- listener: The function to be called when the given event is emitted.
For example, let's say we want to listen for a "click" event:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('click', () => {
console.log('Clicked!');
});
myEmitter.emit('click'); // Output: Clicked!
The "once" Listener
The "once" listener is similar to the "on" listener, but it only listens for the specified event once. After the event is emitted and the attached function is executed, the "once" listener is automatically removed from the event emitter.
The syntax of the "once" listener is as follows:
emitter.once(eventName, listener)
- eventName: The name of the event to listen for.
- listener: The function to be called when the given event is emitted.
For example:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.once('click', () => {
console.log('Clicked!');
});
myEmitter.emit('click'); // Output: Clicked!
myEmitter.emit('click'); // Nothing happens
As you can see, the "once" listener was only triggered once, and then automatically removed from the event emitter.