Callback Concept And Events In Node.js

Today, I will explain about callbacks and events in NodeJS. People who are new to NodeJS, please read my previous article, NodeJS - Getting Started With Some Basic Functions, first.

Callback Concept

A function in NodeJS is either synchronous or asynchronous. An asynchronous function is a function which has the functionality to call events when they complete the execution. The asynchronous function does not wait for any task to complete, it continues its execution with next instruction.

Callback function is a function which is called automatically after the completion of the execution of a time-intensive process. We can understand it by one example -  reading a text file using NodeJS. Here, we assume that the text file is big so the process of reading this file is time-consuming. So, if we are to take a normal synchronous function for reading this text file, how it works is shown in the below example.

Our text file contains the following content.

Exetext.txt

Node.js

CallbackExample.js

  1. var fs = require('fs');  
  2. console.log('Program Started...')  
  3. var content = fs.readFileSync('Exetext.txt');  
  4. console.log(content.toString());  
  5. console.log('Program Ended')  

Now, run this program and check the output.

Node.js

From the above output, we can say that for the first “Program started…” is printed, then the file content is printed and then, the "Program Ended" is printed. Here, the file is big and takes 9-10 seconds to read this text file. Thus, this program goes into the awaited state during reading of the file. No other operation is executed during this time. This is executed at the next instruction. So, it is called synchronous method.

Now, we are to read this file using callback process or the asynchronous method,  as shown in the below example.

CallbackExample2.js

  1. var fs = require('fs');  
  2. console.log('Program Started...')  
  3. fs.readFile('Exetext.txt'function(error, data) {  
  4.     if (error) {  
  5.         console.error(error);  
  6.         return;  
  7.     }  
  8.     console.log(data.toString());  
  9. });  
  10. console.log('Program Ended...');  

Now, run this example and check output as in the below image.

Node.js

Here, you can see that first “Program started…” is printed, then “Program ended” is printed and then, the text file content is printed. So here, when the program is executing, the command for reading a file does not wait for this operation to complete but it continues its execution with the next instruction. So, the program does not go into waited state or block state. Ones the file reading is completed, it automatically calls the callback function and it prints this text file content. This type of method is called the asynchronous method.

In simple words, we can say that the callback function is not blocking your program for a time-consuming process. When a time-consuming task is over, it prints its output.

Events in Node.js

Events in NodeJS are same as a callback. A callback function is called when a function execution is completed where the events have to be fired based on the observer. Every event has listeners and when an event is fired its related listener function starts the execution. Below is some syntax for generating and firing events.

  1. For creating a new event

    var event=require(‘events’);
    var eventEmitter=new event.EventEmitter();

  2. For assigning any function to events. So, when this event is fired, the function gets executed.

    eventEmitter.on(‘eventName’,functionName);

  3. For firing the events.

    eventEmitter.emit(‘eventName’);

We are taking one example for better understanding.

EventExamle.js

  1. var event = require('events');  
  2. var evetnEmitter = new event.EventEmitter();  
  3. console.log('Function started...');  
  4. //  Add listener function for Sumof2Number event  
  5. evetnEmitter.on('Sumof2Number'function(num1, num2) {  
  6.     console.log('Sum of both Number : ' + (Number(num1) + Number(num2)));  
  7. });  
  8. //  Add listener function for Mulof2Number event  
  9. evetnEmitter.on('Mulof2Number'function(num1, num2) {  
  10.     console.log('Multiplication of both Number : ' + (Number(num1) * Number(num2)));  
  11. });  
  12. //  Call or fire both event.  
  13. evetnEmitter.emit('Sumof2Number''10''20');  
  14. evetnEmitter.emit('Mulof2Number''10''20');  
  15. console.log('Function Ended...');  

Now, run the above program which shows the output as below.

Node.js

There is also some more property for event like as below.

  1. addListener(event,listener)
    Add any listener to any event.

  2. Once(event,listener)
    Add one time listener to any event

  3. removeListener(event, listener)
    Remove listener from any event.

  4. removeAllListeners([event])
    Remove all listeners from any event

  5. setMaxListeners(n)
    Set maximum limit for listener on any event

  6. listeners(event)
    Get list of all the listeners of any event.

Thanks for reading my article. I hope you have understood the callback and event concept in NodeJS. If you have any query regarding the above discussion, please feel free to ask in comment box.


Similar Articles