CRUD with File System Create, Read, Update, Delete Files
Learn how to perform Create, Read, Update, and Delete operations using Node.js's built-in fs
module. We'll also handle terminal inputs to do these operations dynamically.
Basic File Operations
const fs = require("fs");
Create New Files
fs.writeFileSync("files/apple.txt", "This is fruit");
fs.writeFileSync("files/banana.txt", "This is fruit");
writeFileSync()
creates files. If file already exists, it will overwrite.
Delete a File
fs.unlinkSync("files/banana.txt");
unlinkSync()
removes a file.
Read a File
const data = fs.readFileSync("files/apple.txt", "utf-8");
console.log(data);
readFileSync()
reads file content. "utf-8"
ensures readable string output.
Update a File
fs.appendFileSync("files/apple.txt", " and this is good for health");
appendFileSync()
adds new content to existing file.
CRUD Operations with Terminal Input
Now let’s make this dynamic — use terminal commands like Write
, Read
, update
, or delete
.
const fs = require("fs");
const operation = process.argv[2];
process.argv[]
gives command-line input.
Create File from Terminal
node index.js Write fileName "your content"
if (operation === "Write") {
const name = process.argv[3];
const content = process.argv[4];
fs.writeFileSync(`files/${name}.txt`, content);
console.log("File Created");
}
Read File from Terminal
node index.js Read fileName
else if (operation === "Read") {
const name = process.argv[3];
const data = fs.readFileSync(`files/${name}.txt`, "utf-8");
console.log(data);
}
Update File from Terminal
node index.js update fileName "new content"
else if (operation === "update") {
const name = process.argv[3];
const content = process.argv[4];
fs.appendFileSync(`files/${name}.txt`, content);
}
Delete File from Terminal
node index.js delete fileName
else if (operation === "delete") {
const name = process.argv[3];
fs.unlinkSync(`files/${name}.txt`);
}
Fallback Case
else {
console.log("Operation not found");
}
Example Test
node index.js Write hello "This is demo"
node index.js Read hello
node index.js update hello " updated!"
node index.js delete hello