Find your content:

Search form

Learn node.js simple way - Callback concepts

 
Share

Node.js is supporting asynchronous callback methods most of the places instead of synchronous. If you write a program in synchronous way it blocks the execution. For example, 

Create a file called "test.txt" and store the below data.

I am interested in learning Node.js. I am happy that I am making progress.

 

Create a file called "callback_example.js" and type the below code.

var fs = require('fs');
var content = fs.readFileSync("test.txt");
console.log(content.toString());
console.log('Done');

in the above code we use the nodejs builtin module called "fs" to do file operation then calling fs.readFileSync('test.txt') method to read the content. 

What happen is until read operation is over it blocks the code execution. Once it completes the read operation from file then it move to next and execute.

What happen if file size huge and system is taking 2mins to read the entire file? - It blocks the execution for 2mins.- This is not recommended.

Following non-blocking pattern is recommended. Assign a callback to the read operation so that once read is complete it execute the callback meanwhile remaining statements get executed or program gets ended.

var fs = require('fs');
fs.readFile('test.txt', function(err, content){
  if(err) 
    return console.error(err);
  console.log(content.toString());
	
});
console.log('Program ended');

My Block Status

My Block Content