Node JS Callback Example

Node JS is an asynchronous JavaScript framework, all the actions in Node app can not block the code execution flow. This can make the system more efficient and faster. So node JS use callback functions heavily to make the design available. This article will tell you what callback is and how it works in Node JS application.

1. What Callback Is?

In node app, callback is a JavaScript function object which will be invoked after action complete. So if you want to use callback for a node action, you can follow below steps.

  1. Create a JavaScript function object with code in it’s body as the callback function. There are generally two input parameters for the callback function, the first parameter is the error object if invoker function throw errors during process, the second parameter is the return data of the invoker function.
    function callback_function(error, result)
    {
        console.log("This is the callback function.");
    }
  2. Use above function as the callback parameter for node functions. Generally the callback parameter is the last input parameter of node function.
    var file_system = require('fs');
    
    file_system.readFile('./async-example.js', callback_function);
  3. So when readFile method complete success or throw errors during file reading, the callback_function will be invoked with error and result input parameters.

2. Node Callback Function Example.

This example will show you the difference between block code and none block code in Node JS.

2.1 Block JS Code.

Code will wait for the read file action complete then to continue, if the file is too large this style can make the code execution block for a long time.

console.log("App start.")

// Include node fs module.
var file_system = require('fs');

// Record start time.
var start_time = new Date();

// Read this file.
var file_path = './test.txt';

// Block read file until complete.
var result = file_system.readFileSync(file_path);

// Get result data length.
var length = result.length;

// Print length to console.
console.log("File data length is " + length);

// Record end time.
var end_time = new Date();

// Get delta time.
var delta_time = end_time.getMilliseconds() - start_time.getMilliseconds();

// Print delta time and exit.
console.log("App exit with execution time is " + delta_time);

Below is the output when execute above code.

App start.
File data length is 39675692
App exit with execution time is 24

2.2 None Block JS Code.

Use callback function when read file complete, this can make the code execution efficient without block.

// This is the callback function used by fs readFile method.
function callback_function(error, result)
{
    console.log("This is the callback function.");

    if(error)
    {
        console.error(error);
    }else
    {
        var data = result.toString();
        var data_length = data.length;
        console.log("File data length is " + data_length);
    }
}

console.log("App start.")

// Include node fs module.
var file_system = require('fs');

// Record start time.
var start_time = new Date();

// Read this file.
var file_path = './test.txt';

// None block read file, invoke callback function when read file complete.
file_system.readFile(file_path, callback_function);

// Record end time.
var end_time = new Date();

// Get delta time.
var delta_time = end_time.getMilliseconds() - start_time.getMilliseconds();

// Print delta time and exit.
console.log("App exit with execution time is " + delta_time);

Below is the output of none block JS code, we can see the execution time is so short so you can execute other code after readFile method. And the callback function is complete after app exit.

App start.
App exit with execution time is 1
This is the callback function.
File data length is 39675643

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.