Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Callbacks in NodeJs

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 138
    Comment on it

    A callback is a function which is called after completion of a current running task. In Nodejs, all APIs are fully supports the callbacks asynchronous i.e. Non-Blocking Code features of NodeJs.

    Due to Non-Blocking features NodeJs makes highly scalable and processed high number of requests without waiting for any function response .

    It will more cleared by Blocking and Non-Blocking examples...

    Blocking Code Example


    Commands To Install Nodejs on Ubuntu

     sudo apt-get update
     sudo apt-get install nodejs
     sudo apt-get install npm

     

    Lets suppose we have created a txt file named "message.txt" as following..


    Data Intensive Real time Applications (DIRT)
    Data Streaming Applications
    JSON APIs based Applications
    Single Page Applications

     

    Now, Create a js file named test_one.js which has the following code:

    var fs = require("fs");
    var data = fs.readFileSync('message .txt');  //Called  synchronousaly
    console.log(data.toString());
    console.log("Here is program ended");

    Now run the "test_one.js"

    $ nodejs  test_one.js


    The output is...

    Data Intensive Real time Applications (DIRT)
    Data Streaming Applications
    JSON APIs based Applications
    Single Page Applications
    Here is program ended


    This code is run line by line as showing in output.

     

    Non-Blocking Code Example


    Create a  "test_two.js" file having following code

    var fs = require("fs");
    fs.readFile('message.txt', function (err, data) {
        if (err) return console.error(err);
        console.log(data.toString());
    });
    console.log("Here is program ended");


    Now run the "test_two.js" by command

    $ nodejs  test_two.js and see the output

    The output is...

    Here is program ended
    Data Intensive Real time Applications (DIRT)
    Data Streaming Applications
    JSON APIs based Applications
    Single Page Applications

    In this example, controller does not wait for complete file reading but it just jumped to print "Here is program ended" and at the same time program without blocking continues reading the file.

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: