Reputation: 141
I have an issue where when I use the fs method fs.appendFileSync(example.json, jsonString, {'flags': 'a+'});
it will write the data to the JSON file... But not in the array I need the data to be in... When I run the code the JSON files contents will look like this
{people:[ {where I want the data to go} ] }{data is written here}
I have no idea as to how to specify that i need the data to be inside the array people... I also have the issue of multiple objects being in the array... They need to have commas how would I also do that?
Upvotes: 0
Views: 38
Reputation: 367
method -1 read that file in some variable. then add your data in that variable which is json. then rewrite file.
method - 2 use fs.write provide position where data need to be added.
fs.writeSync(fd, string, position)
position will be fixed and calculate it based on your json.
Upvotes: 1
Reputation: 86
You can't modify the content of the file by appending to it. You have to read all the data into a object, modify it an then overwrite the contents. See this for a general idea.
const fs = require('fs');
const data = require('./file.json') // node will parse json automatically
data.people.push({}) // the new data you want in the array
fs.writeFileSync('file.json', JSON.stringify(data))
Upvotes: 1