I\'ve been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?
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');
writeFile ('./my_data.json' , {id:1, name:'my name'} )
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');
data = {id:1, name:'my name'}
file_path = './my_data.json'
append_data (file_path , data )
async function append_data (filename , data ) {
if (fs.existsSync(filename)) {
read_data = await readFile(filename)
if (read_data == false) {
console.log('not able to read file')
}
else {
read_data.push(data)
dataWrittenStatus = await writeFile(filename, read_data)
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
else{
dataWrittenStatus = await writeFile(filename, [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
}
}