Skip to content
the poor coder

what is on and once in node

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC