fs system
Sun Jul 23 2023 09:14:47 GMT+0000 (Coordinated Universal Time)
Saved by @nelson22
const fs = require('fs'); // read file fs.readFile('./docs/sample.txt', (err, data) => { if(err){ console.log(err); } console.log(data.toString()); }) console.log("this is last line"); // node will not wait for the function to excute, it will carry on with rest of the code and then come back when the file is read. ------------------------------------------------------------ // write file fs.writeFile('./docs/blog1.txt', 'This is blog line', () => { console.log('File was written'); }) // if blog1.txt doesent exist, then node will create the file instead of giving an error. ------------------------------------------------------------ // create folder if(!fs.existsSync('./assets')){ fs.mkdir('./assets', (err) => { if(err){ console.log(err) } console.log("folder created"); }) }else{ fs.rmdir('./assets', (err) => { if(err){ console.log(err); } console.log('folder deleted'); }) } // existsSync will check if the file exists ------------------------------------------------------------ // delete file if(fs.existsSync('./docs/deleteme.txt')){ fs.unlink('./docs/deleteme.txt', (err) => { if(err){ console.log(err) } console.log('file deleted'); }) } ------------------------------------------------------------ // read stream const readStream = fs.createReadStream('./docs/lorum.txt', {encoding: 'utf8'}) readStream.on('data', (chunk) => { console.log(chunk); }) ------------------------------------------------------------ // write stream const writeStream = fs.createWriteStream('./docs/write.txt'); const readStream = fs.createReadStream('./docs/lorum.txt', {encoding: 'utf8'}) readStream.on('data', (chunk) => { writeStream.write('New chunk'); writeStream.write(chunk); }) ------------------------------------------------------------ // piping const writeStream = fs.createWriteStream('./docs/write.txt'); const readStream = fs.createReadStream('./docs/lorum.txt', {encoding: 'utf8'}) readStream.pipe(writeStream);
Comments