I would like to store JSON in a textfile. Using:
let obj = {'column':empty,'ppas':ppa};
await myFunctions.addToStorage(obj);
async function addToStorage(obj) {
const fs = require("fs");
fs.readFile("storage.json", function (err, data) {
var json = JSON.parse(data);
json.push(obj);
fs.writeFile("storage.json", JSON.stringify(json), function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
});
}
storage.json contains:
{"column":"0:lubbock:LW2-4$","ppas":[{"ppa":50000,"url":"/"},{"ppa":51724.137931034486,"url":"/lubbock"}]}
when I run the program I get:
json.push(obj);
^
TypeError: json.push is not a function
at /home/....functions.js:5:10
I can see that, the problem is that the I'm trying to stored item in storage.json is a stringified object not a stringified array of objects.
How do I set up the project so for the first object you create an array (like if storage.json does not exist)and subsequent objects are added to the array. Is there a commonly used approach to this?
[].json.ppas.push?