There are 2 ways to read files in node.js
1)Read synchronously:Used in the cases where file need to be read before any further processing . eg-any config file.
2)Read Asynchronously(Default):-read file in a separate thread.
Read AsyncSynchronously
First we need to include file system object using require. Now we will call readFile method of file system.This has 2 parameters
1)location of the file.
2) callback function :This will notify us when we successfully read it.
1)Read synchronously:Used in the cases where file need to be read before any further processing . eg-any config file.
2)Read Asynchronously(Default):-read file in a separate thread.
Read AsyncSynchronously
First we need to include file system object using require. Now we will call readFile method of file system.This has 2 parameters
1)location of the file.
2) callback function :This will notify us when we successfully read it.
First we need to include file system object using require. Now we will call readFileSync method of file system.This has one parameter -location of the file.console.log("--------Async Reading------------------"); console.log("Started Reading File..."); console.log("Reading File Asynchronously"); var content=fs.readFile('read.js',function(error,data) { if(error) { console.log(error); } else { console.log("Content \n "+data); } } ); console.log("-------- End Async Reading-------------");
var fs=require('fs'); console.log("--------Synchronously Reading------------------"); console.log("Started Reading File..."); console.log("Reading File Synchronously"); var content=fs.readFileSync('read.js'); console.log("Content Printed First:-- \n "+content); console.log("--------End Synchronously Reading--------------");
No comments :
Post a Comment