Loading, please wait...

Callback Function in Node.js

Callback Function in Node.js (Asynchronous Function)

Callback function defines another function. It is an asynchronous equivalent for a function. It is called at the completion of a task.

In Node.js, once file I/O is complete, it will call the callback function. There is no blocking, holding or wait for File I/O. This makes Node.js highly adaptable and scalable, as it can process a high number of a request without waiting for any function to return a result.

Blocking code example (Synchronous function)

Create a text file named txtwith the following content –

Example of blocking code….

Then run the above code. It reads the file and then only it proceeds to end the program.

Blocking programs executes in sequence. According to programming point of view, it is easier to implement the logic. It first read a text.txt file and then print “program Ended”.

Non-Blocking code example:

Create a text file named text.txt having the following content:

Example of the callback:

Run above program…

Fs module is built in a module of Node.js. It is used to work with a file system of your computer. It can be used fs.stat() function to get file information of text.txt which give information about file size, created date, last modified date…etc. We can take any function like read File(), write File(),append File(),open() etc. fs.stat() function takes two arguments. The first argument is the path of the file and the second argument is a function, which is a callback function.

fs.stat() find whether the file exists or not, then it will try to get all information about that file. If it successfully gets all information then the data is passed into stat parameter of a callback function. If some error happens in the process, that error is passed into err parameter of a callback function. After dealing with the path, callback function gets adjured.

Callback function work procedure:

We can pass a function around like variables and return in a function and use them in another function. When w callback function is pass as an argument to another function, it means we are only passing the function definition, not executing the function in the parameter.

Why use callback Function in node.js?

A callback function is used in an asynchronous manner, it is called at the completion of the given task, and this call function prevents blocking.