Tuesday, July 5, 2016

Reading & Writing File in NodeJs

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.
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-------------");
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.
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