Reputation: 3
It seems like "notes = JSON.parse(fs.readFileSync("notes-data.json"))" line of my code is not working as it should...
When I add new notes it should add on to the array in the .json file, but it just replaces the previous note.
let addNote = (title, body) => {
let notes = [];
let note = {
title,
body
};
notes.push(note);
fs.writeFileSync("notes-data.json", JSON.stringify(notes));
notes = JSON.parse(fs.readFileSync("notes-data.json"))
};
Thank you in advance
Upvotes: 0
Views: 153
Reputation: 351328
If you want to add to the file contents, then you should really read the content before doing anything else:
let addNote = (title, body) => {
let notes;
try {
notes = JSON.parse(fs.readFileSync("notes-data.json")); // <---
} catch(e) {
notes = [];
}
let note = {
title,
body
};
notes.push(note);
fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};
Upvotes: 3