Is there away to write an array in NodeJs (Just the data) to a JSON file without replacing other arrays or data? I have tried:
let homeFile_JsData = {
id: id,
title: title,
author: user
}
let homeFile_data = JSON.stringify(homeFile_JsData);
fs.writeFileSync("json/home.json", homeFile_data, "UTF-8",{'flags': 'a '});
But it replaces the entire file! Is there a way?
File after writing:
{"id":"2", "title":"2nd_title", "authour":"2nd_me"}
But I would like it to look like:
"array" [
{"id":"1", "title":"1st_title", "authour":"1st_me"},
{"id":"2", "title":"2nd_title", "authour":"2nd_me"}
]
CodePudding user response:
If you just want to add a new row of data, then JSON isn't really the right format. It is not design for incremental updates and thus you generally have to read the entire JSON, parse it into a Javascript object, modify the Javascript object, convert back to JSON, then write the entire file of JSON.
If you are just adding a new element to the end of an array at the end of the JSON, you could (very carefully) find a way to overwrite just the right amount of JSON to add onto the end of it, but that's not really a good way to do things as, small changes in the structure could break the code.
On the other hand, for just adding a new row of data, the CSV text format can do that fairly easily as each line in the file represents a record and you can just add new lines of data onto the end of the file with fs.appendfileSync()
at any time. You would then have to get a parser for the CSV data since nodejs doesn't have a CSV parser built in, but there are numerous modules that can do that on NPM or you could even write your own as CSV isn't difficult to parse.
Of course, a more scalable solution would involve using a simple database that lets you incrementally modify, add or delete any of the data and the database handles the disk storage of the data entirely for you. It, of course, also provides all sorts of other features such as queries and concurrency protection, etc...