Reputation: 53
Im triying to write a JSON object to a DB with FS but it´s not working as expected. What i want to do is write the JSON data inside this: []
Example:
[
{"name":"jhon"},
{"name":"jhonathan"}
]
Thanks.
Upvotes: 1
Views: 508
Reputation: 2554
The comment you provided doesn't make much sense, because the JSON data you provided in the post and in the comments is completely different. But I get the gist of it. I guess you have a JSON file containing an array and you want to push new items to it. Let's do this.
The thing is, when you call fs.appendFile
, you're only writing to the end of the file. You're not following JSON format by doing so.
You need to do this:
I'll call the synchronous methods for simplicity's sake, but you should be able to convert it to async quite easily.
const path = __dirname + 'db.json'
// Reading items from the file system
const jsonData = fs.readFileSync(path)
const items = JSON.parse(jsonData)
// Add new item to the item list
items.push(newItem)
// Writing back to the file system
const newJsonString = JSON.stringify(items)
fs.writeFileSync(path, newJsonString)
Upvotes: 1