Reputation: 128
How to push object inside an array while writing to a file in Node Js? I currently have the following working code
fs.appendFile("sample.json", JSON.stringify(data, undefined, 2) + ",");
where data is an object, like
{
name:'abc',
age: 22,
city: 'LA'
}
Upon appending, which results the following
{
name:'abc',
age: 22,
city: 'LA'
},
{
name:'def',
age: 25,
city: 'MI'
},
I see 2 problems here. 1. The trailing comma at the end 2. The inability to form an array and push the object into it
Any leads would be appreciated
Upvotes: 1
Views: 7277
Reputation: 342
Append will append your data to a file and here data is being treated as a string and all appends will be equal to concating string to another string.
Instead, here the file needs to be read first and converted to a data-structure for this example it can be an array of objects and convert that data-structure to string and write it to file.
To write to the file
fs.writeFileSync('sample.json', JSON.stringify([data], null, 2));
sample.json
[
{
"name": "abc",
"age": 22,
"city": "LA"
}
]
Read from file
const fileData = JSON.parse(fs.readFileSync('sample.json'))
fileData.push(newData)
Write the new data appended to previous into file
fs.writeFileSync('sample.json', JSON.stringify(fileData, null, 2));
sample.json
[
{
"name": "abc",
"age": 22,
"city": "LA"
},
{
"name": "abc",
"age": 22,
"city": "LA"
}
]
Upvotes: 7