So im trying to push an array, to a JSON file which is already in an array format.
The code im using to attempt this is:
needle.get("https://bpa.st/raw/VHVQ", function(response, body){
let testlist = require('../testlist.json')
let list = response.body;
let listarray = list.split("\r\n")
for (var i of listarray) {
testlist.push(i);
}
When my app is running it shows testlist.json as:
["1", "2", "this", "is", "an", "example", "for", "stackoverflow"]
Now it seems to work fine, it acts like its updated the array, but if I check, it hasn't, and if I restart my app then it resets to the original un-edited version.
testlist.json looks like this:
["1", "2"]
and after, im trying to make it edit the json file to look like this:
["1", "2", "this", "is", "an", "example", "for", "stackoverflow"]
When you import the contents of testlist.json into the variable testlist using require(), you are loading the file's contents into memory. You will need to write back to the file after you have made changes to the testlist variable if you want your modifications to persist. Otherwise, the changes that you make will be lost when the program's process exits.
You can use the writeFileSync() method from the fs module, as well as JSON.stringify(), to write testlist back into the testlist.json file:
const fs = require("fs");
let testlist = require("../testlist.json");
// Your code where you modify testlist goes here
// Convert testlist to a JSON string
const testlistJson = JSON.stringify(testlist);
// Write testlist back to the file
fs.writeFileSync("../testlist.json", testlistJson, "utf8");
Edit: You should also use the readFileSync() method (also from the fs module), and JSON.parse() to perform the initial reading of the JSON file, rather than require().
// This line
let testlist = require("../testlist.json");
// Gets replaced with this line
let testlist = JSON.parse(fs.readFileSync("../testlist.json", "utf8"));
You have to use JSON.parse as well as fs.readFileSync because when you are reading the file, it is read as a string, rather than a JSON object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With