Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Example of blocking program in node

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 245
    Comment on it

    Here we will learn about callback function in node. Callback functions are called once the given task is completed. Callback functions are used highly in Node. It is also known as blocking. In node.js all APIs support callbacks.

    Example: Let us take a function which will start reading a file and immediately return the control to execution environment so that next command can be executed. On completion of file I/O, the callback function will be called and the content of the file is passed as a parameter. hence there is no waiting or blocking for File I/O.

     

    Example of blocking:

    Let us create a text file file_1.txt. Now write some content in the file_1.txt

    Let us write the below content:

    Content for blocking example: The runtime environment interprets JavaScript using Google's V8 JavaScript engine.

     

    Now create a js file demo.js and write the following code:

    var filesys_b = require("fs"); /*importing a file system  module */
    
    var output = filesys_b.readFileSync('file_1.txt'); 
    
    console.log(output.toString());
    console.log("This is end of the code..");

     

    Now execute the following command

    username@machinename:~$ cd path of the file
    username@machinename: path of the file$ node demo.js

    The above example explains the concept of blocking calls here the program blocks until it reads the file_1.txt and after that, it proceeds to the code console.log("This is end of the code..");

     

    Output:

    Content for blocking example: The runtime environment interprets JavaScript using Google's V8 JavaScript engine.

    This is the end of the code.

 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: