Node.js Callback Functions
The direct manifestation of asynchronous programming in Node.js is the callback.
Asynchronous programming relies on callbacks to achieve its goals, but it cannot be said that using callbacks makes the program asynchronous.
Callback functions are invoked after the task is completed. Node.js uses a large number of callback functions, and all Node APIs support callback functions.
For example, we can read a file while executing other commands, and when the file reading is complete, we return the file content as a parameter to the callback function. This way, the code execution does not block or wait for file I/O operations. This significantly improves the performance of Node.js, allowing it to handle a large number of concurrent requests.
Callback functions typically appear as the last parameter of a function:
function foo1(name, age, callback) { }
function foo2(value, callback1, callback2) { }
Blocking Code Example
Create a file input.txt
with the following content:
tutorialpro.org website address: www.tutorialpro.org
Create a main.js
file with the following code:
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program execution finished!");
The execution result of the above code is as follows:
$ node main.js
tutorialpro.org website address: www.tutorialpro.org
Program execution finished!
Non-blocking Code Example
Create a file input.txt
with the following content:
tutorialpro.org website address: www.tutorialpro.org
Create a main.js
file with the following code:
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program execution finished!");
The execution result of the above code is as follows:
$ node main.js
Program execution finished!
tutorialpro.org website address: www.tutorialpro.org
Through these two examples, we understand the difference between blocking and non-blocking calls. The first example executes the program only after the file reading is complete. In the second example, we do not need to wait for the file reading to complete, allowing us to execute the following code while reading the file, thereby significantly improving the program's performance.
Therefore, blocking is sequential execution, while non-blocking does not require sequential execution. So, if you need to handle parameters of the callback function, you need to write it within the callback function.