Woosung Koh
Woosung Koh

Reputation: 3

new data added to JSON keeps replacing previous

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"))
};

Code Screenshot: enter image description here

Thank you in advance

Upvotes: 0

Views: 153

Answers (1)

trincot
trincot

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

Related Questions