0

below is a piece of js code.When I run it with "node" command. It displays. "notes.filter" is not a function.If I comment "JSON.parse" line. It works. But video tutorial does have this line. So I am quite confused here. Could any one helps here. Thanks a lot.

var addNote = (title, body) => {
  var notes = [];
  var note = {
    title,
    body
  }

  try {
    var notesstring = fs.readFileSync('notes-data.json');
    notes = JSON.parse(notesstring);
  } catch (e) {

  }

  console.log(Array.isArray(notes));
  var duplicateNote = notes.filter((note) => note.title === title);
  if (duplicateNote.length === 0) {
    notes.push(note);
    fs.writeFileSync('notes-data.json', JSON.stringify(note));
  }
};
4
  • What's the output of node --version if you run it from the command line? Commented May 1, 2017 at 3:26
  • 1
    What is the content of notes-data.json? What is the output of console.log(Array.isArray(notes)); in the case where you use JSON.parse()? If you comment the JSON.parse() line then the notes variable stays as the empty array it was originally assigned. Commented May 1, 2017 at 3:26
  • @nnnnnn Content is probably whatever has been put there using this function on the line fs.writeFileSync... Commented May 1, 2017 at 3:29
  • 1
    You're writing out a single note, but then trying to read in an array. What are you trying to do? Do you want to write out the array with the additional new element? Then do that. Commented May 1, 2017 at 3:36

1 Answer 1

1

I had the same problem while going through the course but ended up fixing it.

For some reason, I was getting back bad JSON, and so I had to delete the note-data.json file, and then re-run the app. This fixed it for me!

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to SO! To improve your answer you could investigate why deleting the notes-data.json file is required and possibly provide the new code where it runs without having to perform that manual step. Also in your answer you state "note-data.json" whereas the question mentions "notes-data.json".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.