home PYTHONJAVA
 

Node.js Callbacks


Callback is an asynchronous equivalent for a function. It is called toward the finish of each assignment. In Node.js, callbacks are commonly utilized. All APIs of Node are written in a manner to supports callbacks. For instance: when a function begin execution environment immediately , it restores the control to execution condition promptly so the following guidance can be executed.

In Node.js, when record I/O is finished, it will call the callback work. So there is no blocking or hang tight for File I/O. This makes Node.js exceptionally versatile, as it can process high number of solicitation without trusting that any function will return result.

Blocking Code Example

Follow these steps:

  1. Create a text file named input.txt having the following content:
  2.     Free Online Tutorials Welookups provides tutorials like java tutorial, android, javascript, ajax, sql, python, php, c++ language etc. for beginners
    
    Node.js callbacks 1

    Non Blocking Code Example

    Follow these steps:

    1. Create a text file named input.txt having the following content:
    2.     
          Free Online Tutorials Welookups provides tutorials like java tutorial, android, javascript, ajax, sql, python, php, c++ language etc. for beginners
      
    3. Create a JavaScript file named main.js having the following code:
      1. var fs = require("fs");  
      2.   
      3. fs.readFile('input.txt', function (err, data) {  
      4.     if (err) return console.error(err);  
      5.     console.log(data.toString());  
      6. });  
      7. console.log("Program Ended");  
    4. Open the Node.js command prompt and execute the following code.
      1. node main.js   
    Node.js callbacks 2





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.