Node.js CURD Operations with File System
The Node.js file system module allows you to work with a file system on your computer. We can include the File System module by using the require() method.
const fs=require('fs');
The fs module provides the API for interacting with a file system in a manner closely modeled around standard POSIX (Portable Operating System Interface) functions.
we can use the fs module for CURD Operations.
- C=> Create,
- U=> Update,
- R=> Read,
- D=> Delete
✅ Create A file Using fs module
const fs=require('fs');
// Create file with file name is newFile.txt
fs.writeFileSync('newFile.text',"New File Created By Usnig Node.js File System")
Output:-
Note:- By Defaults node.js File System access our projects root directory we can easily changed it by using path() module
const path=require('path');
Example:-
// modules
const fs=require('fs');
const path=require('path');
//directory path
const fileDirectory=path.join(__dirname,'Operations')
// Create file with file name is newFile.txt
const filePath=`${fileDirectory}/newFile.text`
fs.writeFileSync(filePath,"New File Created By Usnig Node.js File System")
Output:-
✅ Update File Update Files The File System module has methods fs.appendFile()
// modules
const { error } = require('console');
const fs=require('fs');
const path=require('path');
//directory path
const fileDirectory=path.join(__dirname,'Operations')
// Create file with file name is newFile.txt
const filePath=`${fileDirectory}/newFile.text`
fs.appendFile(filePath, ' and here we are using fs.appendFile() for updating file text',
(error)=>{
if(!error){
console.log('File Updated Successfuly...')
}
else{
console.log('Samething is Wrong...')
}
})
console:-
Output:-
✅ Read File The File System module has methods fs.readFile() for read files.
// modules
const { error } = require('console');
const fs=require('fs');
const path=require('path');
//directory path
const fileDirectory=path.join(__dirname,'Operations')
// Create file with file name is newFile.txt
const filePath=`${fileDirectory}/newFile.text`
fs.readFile(filePath,'UTF-8',(err, data)=>{
if(data){
console.log(data)
}
else(
console.log(err)
)
})
Console :-
✅ Delete The File System module has methods fs.unlinkSync() for delete file.
// modules
const { error } = require('console');
const fs=require('fs');
const path=require('path');
//directory path
const fileDirectory=path.join(__dirname,'Operations')
// Create file with file name is newFile.txt
const filePath=`${fileDirectory}/newFile.text`
// Delete file
fs.unlinkSync(filePath,
console.log("File Deleted Successfuly")
);
Console:-
Subscribe to my newsletter
Read articles from Ravi Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by