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
CallbackExample.js
- var fs = require('fs');
- console.log('Program Started...')
- var content = fs.readFileSync('Exetext.txt');
- console.log(content.toString());
- console.log('Program Ended')
Now, run this program and check the output.
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
- var fs = require('fs');
- console.log('Program Started...')
- fs.readFile('Exetext.txt', function(error, data) {
- if (error) {
- console.error(error);
- return;
- }
- console.log(data.toString());
- });
- console.log('Program Ended...');
Now, run this example and check output as in the below image.
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.
- For creating a new event
var event=require(‘events’);
var eventEmitter=new event.EventEmitter();
- For assigning any function to events. So, when this event is fired, the function gets executed.
eventEmitter.on(‘eventName’,functionName);
- For firing the events.
eventEmitter.emit(‘eventName’);
We are taking one example for better understanding.
EventExamle.js
- var event = require('events');
- var evetnEmitter = new event.EventEmitter();
- console.log('Function started...');
-
- evetnEmitter.on('Sumof2Number', function(num1, num2) {
- console.log('Sum of both Number : ' + (Number(num1) + Number(num2)));
- });
-
- evetnEmitter.on('Mulof2Number', function(num1, num2) {
- console.log('Multiplication of both Number : ' + (Number(num1) * Number(num2)));
- });
-
- evetnEmitter.emit('Sumof2Number', '10', '20');
- evetnEmitter.emit('Mulof2Number', '10', '20');
- console.log('Function Ended...');
Now, run the above program which shows the output as below.
There is also some more property for event like as below.
- addListener(event,listener)
Add any listener to any event.
- Once(event,listener)
Add one time listener to any event
- removeListener(event, listener)
Remove listener from any event.
- removeAllListeners([event])
Remove all listeners from any event
- setMaxListeners(n)
Set maximum limit for listener on any event
- 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.