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
Blocking Code Example
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
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.
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.
Note :-
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:
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
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.
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).
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.
Trending Tutorials