0

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

beso9595
  • 1,146
  • 3
  • 10
  • 16

1 Answers1

3

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));
};
trincot
  • 317,000
  • 35
  • 244
  • 286