Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Callbacks and Events in Node.js

  • Last Updated : 16 Jan, 2022

In this article, we are going to learn about Callbacks and Events in Nodejs. Both Callback and Events are important concepts of Nodejs. Let’s learn about Callback first.

Callback Concept

A Callback is a function that is called automatically when a particular task is completed. The Callback function allows the program to run other code until a certain task is not completed. The callback function is heavily used in nodeJS. The callback function allows you to perform a large number of I/O operations that can be handled by your OS without waiting for any I/O operation to finish. It makes nodeJS highly scalable. For example: In Node.js, when a function starts reading a file, It’s obviously going to take some time so without waiting for that function to complete, it returns control to the execution environment immediately so to execute the succeeding instruction. Once file I/O gets completed, the callback function will be automatically called hence there will be no waiting or blocking for file I/O.

Note: The callback function is being replaced by async/await these days. 

Syntax:  Let’s see the syntax of the callback function. 

const fs = require("fs");

fs.readFile("file_path", "utf8", function(err, data) {
   if(err) {
       // Handle the error  
   } else {
       // Process the file text given with data
   }
});

Example 1: Code for reading a file synchronously in Node.js. Create a text file input.txt with the following text:

Welcome to GFG.
Learn NodeJS with GeeksforGeeks

Now, create a javascript file name main.js with the following code.

main.js




var fs = require("fs");
var filedata = fs.readFileSync('input.txt');
console.log(filedata.toString());
console.log("End of Program execution");

Now run the main.js to see the result with the following command:

node main.js

Explanation: In this example, we have an fs module of nodeJS that provides the functionality of File I/O operations. With the help of the readFileSync() function, we are able to use the Synchronous approach here, which is also called blocking functions as it waits for each instruction to be complete first before going to the next one. Hence in this example, the function blocks the program until it reads the file and then went ahead with the end of the program.

Output:

GFG

Example 2: Code for reading a file asynchronously in Node.js.  Keep the “input.txt” file the same as before. Here is the code of main.js:

 

main.js




var fs = require("fs");    
fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);
    console.log(data.toString());
});
console.log("End of Program execution");

Now run the main.js to see the result with the following command:

node main.js

Explanation: With the help of the readFile() function, we are able to use the Asynchronous approach here, which is also called non-blocking functions as it never waits for each instruction to complete, rather it executes all operations in the first go itself. Hence in this example, the function runs in the background, and the control is returned to the next instruction. When the background task is completed callback function is called.

Output:

GFG

Events

Each action on the computer is called an event. In nodeJS objects can fire events. According to the official documentation of Node.js, it is an asynchronous event-driven JavaScript runtime. Node.js has an event-driven architecture that can perform asynchronous tasks. Node.js has an ‘events’ module that emits named events that can cause corresponding functions or callbacks to be called. Functions(Callbacks) listen or subscribe to a particular event to occur and when that event triggers, all the callbacks subscribed to that event are fired one by one in order to which they were registered.

The EventEmmitter class: All objects that emit events are instances of the EventEmitter class. The event can be emitted or listened to an event with the help of EventEmitter.

Syntax:

const EventEmitter=require('events');
var eventEmitter=new EventEmitter();

The following table lists all the important methods of the EventEmitter class:

EventEmitter MethodsDescription
eventEmitter.addListener(event, listener) &&
eventEmitter.on(event, listener)
eventEmmitter.on(event, listener) and eventEmitter.addListener(event, listener) are pretty much similar. It adds the listener at the end of the listener’s array for the specified event. Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times. Both functions return emitter, so calls can be chained.
eventEmitter.once(event, listener)It fires at most once for a particular event and will be removed from listeners array after it has listened once. Returns emitter, so calls can be chained.
eventEmitter.emit(event, [arg1], [arg2], […])Every event is named event in nodeJS. We can trigger an event by emit(event, [arg1], [arg2], […]) function. We can pass an arbitrary set of arguments to the listener functions.
eventEmitter.removeListener(event, listener)It takes two argument event and listener and removes that listener from the listener’s array that is subscribed to that event
eventEmitter.removeAllListeners() It removes all the listeners from the array who are subscribed to the mentioned event.
eventEmitter.getMaxListeners(n)It will return the max listeners value set by setMaxListeners() or default value 10.
EventEmitter.defaultMaxListenersBy default, a maximum of 10 listeners can be registered for any single event. To change the default value for all EventEmitter instances this property can be used.
eventEmitter.listeners(event) It returns an array of listeners for the specified event.
eventEmitter.listenerCount() It returns the number of listeners listening to the specified event.
eventEmitter.prependOnceListener()It will add the one-time listener to the beginning of the array.
eventEmitter.prependListener()It will add the listener to the beginning of the array.

Example 1: Code for creating a program of a simple event:

main.js




const EventEmitter = require('events');
// Initializing event emitter instances 
var eventEmitter = new EventEmitter();
  
// Create an event handler:
var EventHandler = function () {
  console.log('Learn nodejs!');
}
  
// Assign the event handler to an event:
eventEmitter.on('event1', EventHandler);
  
// Fire the 'scream' event:
eventEmitter.emit('event1');

Now run the main.js to see the result with the following command:

node main.js

Output:

Example 2: This example, shows the creating and removing of the listener. The EventEmitter instance will emit its own ‘newListener’ event. The ‘removeListener’ event is emitted after a listener is removed.

main.js




// Importing events
const EventEmitter = require('events');
  
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
  
// Register to newListener
eventEmitter.on( 'newListener', (event, listener) => {
    console.log(`The listener is added to ${event}`);
});
  
// Register to removeListener
eventEmitter.on( 'removeListener', (event, listener) => {
    console.log(`The listener is removed from ${event}`);
});
  
// Declaring listener fun1 to myEvent1
var fun1 = (msg) => {
    console.log("Message from fun1: " + msg);
};
  
// Declaring listener fun2 to myEvent2
var fun2 = (msg) => {
    console.log("Message from fun2: " + msg);
};
  
// Listening to myEvent with fun1 and fun2
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);
  
// Removing listener
eventEmitter.off('myEvent', fun1);
  
// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');

Now run the main.js to see the result with the following command:

node main.js

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!