Sunday, September 6, 2020

File operations

 //Read folders and files.js

const fs = require('fs');


//read synchronousy: fs.readdirSync()

fs.readdir('./',(err,content)=>{

  if(err) throw err;

  console.log(content);

});


fs.readFile('global.html','UTF-8',(err,content)=>{

console.log(content);

});


//filewriting.js

const fs = require('fs');

fs.writeFile('./modules/data.html',`\n \n Hello this file has just been created\n\n`,'utf8',(err)=>{

 if(err) return err;

 console.log("The file has been saved");

});

fs.appendFile('./modules/data.html','Extra data','utf8',(err)=>{

 if(err) return err;

 console.log("The file has been saved");

});


//file-creating-directories.js

const fs = require('fs');

fs.access('./views',function(error){

if(error) {

 console.log('folder not found');

 fs.mkdir('views',function(error){

 if(error) return error;

 fs.writeFile('./views/new.html','hello',function(){

  if(error){

   console.log('we could not write');

  }

});

})

}

});


//removing directories and files.js

const fs = require('fs');

fs.rmdirSync('./newDir');

try{

fs.unlinkSync('./newDir1/newfile.js');

}catch(err){

console.log(err+" here is the error");

}


//rename

const fs = require('fs');

fs.renameSync('./newfile2.js','newDir/newfile.js');

fs.renameSync('./newDir/ChildDir','./ParentDir');


No comments:

Post a Comment