Point 1:
If you want to write something into a file.
means: it will remove anything already saved in the file and write the new content. use fs.promises.writeFile()
Point 2:
If you want to append something into a file.
means: it will not remove anything already saved in the file but append the new item in the file content.then first read the file, and then add the content into the readable value, then write it to the file. so use fs.promises.readFile and fs.promises.writeFile()
example 1: I want to write a JSON object in my JSON file .
const fs = require( fs );
const data = {table:[{id: 1, name: my name }]}
const file_path = ./my_data.json
writeFile(file_path, data)
async function writeFile(filename, writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata, null, 4), utf8 );
console.log( data is written successfully in the file )
}
catch (err) {
console.log( not able to write data in the file )
}
}
example2 :
if you want to append data to a JSON file.
you want to add data {id:1, name: my name } to file my_data.json on the same folder root. just call append_data (file_path , data ) function.
It will append data in the JSON file if the file existed . or it will create the file and add the data to it.
const fs = require( fs );
const data = {id: 2, name: your name }
const file_path = ./my_data.json
append_data(file_path, data)
async function append_data(filename, data) {
if (fs.existsSync(filename)) {
var read_data = await readFile(filename)
if (read_data == false) {
console.log( not able to read file )
} else {
read_data.table.push(data) //data must have the table array in it like example 1
var dataWrittenStatus = await writeFile(filename, read_data)
if (dataWrittenStatus == true) {
console.log( data added successfully )
} else {
console.log( data adding failed )
}
}
}
}
async function readFile(filePath) {
try {
const data = await fs.promises.readFile(filePath, utf8 )
return JSON.parse(data)
}
catch (err) {
return false;
}
}
async function writeFile(filename, writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata, null, 4), utf8 );
return true
}
catch (err) {
return false
}
}