Read the file sync and async using Node.js



Reading the file using file system module. we have two options to process synchronous and asynchronous. Here we are testing on synchronous of the node.js. The sequence of code should wait until we read the file sample txt file. For that waiting we are using readFileSync class from File system module.

var file = require("fs");
console.log("Starting...");

var content = file.readFileSync("./sample.txt");
console.log("Content : " + content);
console.log("Keep going ...");

If we run the file in node. First it will print the sample txt and after that only it will print the “Keep going” String. Because it is waiting for the read command finish.

Here we are testing on asynchronous of the node.js. The sequence of code should not wait until we read the sample txt file. For that we are using callback function.

var file = require("fs");
console.log("Starting...");

file.readFile("./sample.txt",
       function (error,data){
           console.log("Contents" + data);
});
console.log("Keep going ...");

This will not wait until read the file So it will print the “Keep going” first . After that only it will return the text file content.

7 comments: