Categories

Nodejs File System Notes

Nodejs File System.

Load module with name ‘fs’

To Read a file use fs.readFile 

To Write a file use fs.writeFile (Note : if file does not exists it will create the file)

existsSync is used to check if file or folder exists

To create a new directory use fs.mkdir

To remove a directory use fs.rmdir

To delete a file use fs.unlink

To read and write stream from readstream to writeStream just use read.pipe(write), In this case we are using pipe

rdStrea.on(‘data’, callback) this is a event on data – basically it tells to act when data comes


const fs = require('fs');

// Read File asynchronous
fs.readFile('./hello.txt',(err, data)=>{
    if(err) console.log(err)

    console.log(data.toString());
});

// write file asynchronous

fs.writeFile('./hello.txt', 'New Message: Hello India', ()=>{
    console.log('file was written')
});



// check if server directory does not exists, if true then create a new Server directory 
if(!fs.existsSync('./Server')){
    fs.mkdir('./Server', (err)=>{
        if(err)console.log(err);
        console.log('Directory created')
    })
}else{
    // delete if directory exits

    fs.rmdir('./Server',(err)=>{
        if(err)console.log(err);
        console.log('directory deleted')
    })
}

// check if file exists then delete it

if(fs.existsSync('./hello.txt')){
    fs.unlink('./hello.txt',(err)=>{
        if(err)console.log(err);
        console.log('file delted')
    })
}

// Read huge amount of data in chunks using streams
// Write stream data to a new file using writestream

const rdStream = fs.createReadStream('./hugetext.txt',{encoding: 'utf8'});
const wrStream = fs.createWriteStream('./hugetext2.txt');

// read stream data in chunks
rdStream.on('data',(chunks)=>{
    console.log(chunks);
})

// using pipe in node for reading and writing stream of data
rdStream.pipe(wrStream);
adbanner