How to Node Js- Callback functions

In this guide, we will learn about the Callback functions in Node js. The callback is an asynchronous equivalent of a function. A callback is called at the completion of each task. In Node.js, callbacks are heavily used. All Node js API are written to supports callback functions.

In Node.js, once file I/O is complete, it will call the callback function. This way Node.js can carry on dealing with other requests while it’s reading the file, making our code non-blocking. An I/O is shorthand for Input and Output and it means accessing anything outside of your application.

 

Blocking Code

Consider the following example, used to read a text file and output the content.

Let’s create a text file named file.txt with the following content on it.

file.txt
     Lorem ipsum dolor sit amet, consectetur adipiscing elit.
     Sed lobortis turpis a nisl volutpat accumsan. 
     Proin vulputate diam quis enim laoreet viverra.

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

main.js
     var fs = require("fs");
     var content = fs.readFileSync('file.txt');

     console.log(content.toString());
     console.log("Execute after reading file content");

Open the Node.js command prompt and execute the following code.

Node Js Command
     node main.js

the program blocks until it reads the file and then only it proceeds to next line of code.

 

Non-Blocking Code

To demonstrate the non-blocking program, Let’s create a text file named file.txt with the following content on it.

file.txt
      Lorem ipsum dolor sit amet, consectetur adipiscing elit.
      Sed lobortis turpis a nisl volutpat accumsan. 
      Proin vulputate diam quis enim laoreet viverra.

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

main.js
	var fs = require("fs");

	fs.readFile('file.txt', function (err, content) {
		 if (err) return console.error(err)
		 console.log(content.toString());
	});
	console.log("Program Ended");

Open the Node.js command prompt and execute the following code.

Node Js Command
       node main.js

The above program does not wait for file reading. it fetches next line of code at the same time, so the program continues reading the file without blocking.

 

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...