Wednesday, October 19, 2016

Executing Simple Node Js program using Syns, Async and CallBacks


1- Sync method
//Simple way to Read File Sync Way
var fs = require('fs');
var content = fs.readFileSync("SiddhuReadMe.txt", "utf8");
console.log(content);
console.log('Reading file text from JS file...');

2- Async Method
In below example we are calling the txt files Async i.e. we are not waiting for function readFile() to complete then execute console.log('Reading file text from JS file...'). We execute console.log and then we display output of readFile once we get the values
//Simple way to Read File ASync Way
var fs = require('fs');
fs.readFile("SiddhuReadMe.txt", "utf8", function(err, content) {
if (err) {
return console.log(err);
}
console.log(content);
});
console.log('Reading file text from JS file...');
3- Callbacks
Call back stands for calling one function from anther. Here in below example we are calling or passing function name as argument i.e. SiddhuMycontent function() from readingfile().
In below example all out code get executed and then we get the reply from our txt files that state that we are not waiting for callback function to execute.
Best scenario to use callback approach is when user want to download the big files and we don;t want our application to stop executing. i.e. we want our application to run parallel while file is downloading.
//Simple way to Read File Callback way i.e. calling function from another function
var fs = require('fs');
var fcontent ;
function readingfile(callback){
fs.readFile("SiddhuReadMe.txt", "utf8", function(err, content) {
fcontent=content;
if (err)
{
return console.error(err.stack);
}
callback(content);
})
};
function SiddhuMycontent() {
console.log(fcontent);
}
readingfile(SiddhuMycontent);
console.log('Reading file text from JS files....');

image2

No comments: