Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





what is Callback function in node.js

How to use callback function?

Callbacks function :

In Node.js, callbacks are generally used.

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

A callback is a function which is called when a task is completed. a callback function allows other code to run in the meantime.

Callback is called when task get completed. Using Callback concept, Node.js can process a large number of requests without waiting for any function to return the result which makes Node.js highly scalable.

For example: In Node.js, when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.

All APIs of Node are written in a way to supports callbacks


Example

File Name : myfile.txt

Hello Developer!!! Learn NodeJS with ItTutorial.

Blocking Code Example

File Name : test.js

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

fs library is loaded to handle file-system related operations. The readFileSync() function is synchronous and blocks execution until finished. The function blocks the program until it reads the file and then only it proceeds to end the program

Output :-

Hello Developer!!!
Learn NodeJS with ItTutorial.
End of Program execution

Example 2 :- Non Blocking Code

Code for reading a file asynchronously (non-blocking code) in Node.js. Create a text file myfile.txt with the following content.

File Name : test.js

var fs = require("fs");

fs.readFile('myfile.txt', function (ferr, filedata) {
if (ferr) return console.error(ferr);
console.log(filedata.toString());
});
console.log("End of Program execution");

fs library is loaded to handle file-system related operations. The readFile() function is asynchronous and control return immediately to the next instruction in the program while the function keep running in the background. A callback function is passed which gets called when the task running in the background are finished.

Output :-

End of Program execution
Hello Developer!!!
Learn NodeJS with ItTutorial.

Note :-

You can see that above two examples explain the concept of blocking and non-blocking calls. The first example shows that program blocks until it reads the file and then only it proceeds to end the program on the other hand in second example, program does not wait for file reading but it just proceeded to print "End of Program execution" and same time program without blocking continues reading the file.

So we can say that, a blocking program executes very much in sequence. It is also easier to implement the logic from programming point of view in block programs. But non-blocking programs does not execute in sequence, so in case a program needs to use any data to be processed


Difference between Events and Callbacks:

Events and Callbacks look similar but the differences lies in the fact that callback functions are called when an asynchronous function returns its result where as event handling works on the observer pattern. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events and event listeners.

How Node Applications Work?

In Node Application, any async function accepts a callback as the last parameter and a callback function accepts an error as the first parameter. Create a text file named myfile.txt

create nodejs file test.js

var fs = require("fs");

fs.readFile('myfile.txt', function (err, data) {
if (err) {
console.log(err.stack);
return;
}
console.log(data.toString());
});
console.log("Program Execution Ended");

Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during the read operation, then the err object will contain the corresponding error, else data will contain the contents of the file. readFile passes err and data to the callback function after the read operation is complete, which finally prints the content.

Program Execution Ended
Hello Developer!!!
Learn NodeJS with ItTutorial.

Callbacks

A callback is a function passed as an argument into another function, which can then be invoked (called back) inside the outer function to complete some kind of action at a convenient time. The invocation may be immediate (sync callback) or it might happen at a later time (async callback).

// Sync callback
function say(callback) {
callback();
}
say(() => { console.log('Hello'); });

more_Work(); // will run after console.log

// Async callback
const fs = require('fs');
fs.readFile('/file.md', function callback(err, data) {
// fs.readFile is an async method provided by Node
if (err) throw err;
console.log(data);
});
more_Work(); // will run before console.log

An async callback may be called when an event happens or when a task completes. It prevents blocking by allowing other code to be executed in the meantime.





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here