Reputation: 95
I have a JSON file that looks like this
{
"name": "John Doe",
"address": "9 School Rd"
}
how do I append this file in node.js? When I try fs.appendFile the JSON file ends up looking like this
{
"name": "John Doe",
"address": "9 School Rd"
},
"nickname": "shmee"
however this is obviously not what I want it to look like. Thanks for your help!
Upvotes: 1
Views: 178
Reputation: 32511
A very simple way of doing this would be to parse in the object as JSON then save back the stringified version to the file.
var data = require('./my-data-file.json'); // Will automatically parse JSON
data.nickname = "shmee";
fs.writeFile('./my-data-file.json', JSON.stringify(data, null, 4), options, callback);
The options and callback are optional but I suggest writing a callback because that will let you know when the data has been saved.
Upvotes: 1