Try statement never passes without throwing error

3050 views javascript
6

In the following block of code, I am trying to get user input and save them in a json file. If the the inserted item is already exists in the file it gets rejected. The issue here is that my programme always executes the catch clause and generate an empty array, although in some situations json file exists and it is ready to be read.

const fs = require('fs');

const loadFile = () => {
  try{
    const stringData = fs.readFileSync('note-data.json', 'utf8');
    return [JSON.parse(stringData)];
  } catch (e) {
    return [];
  }
};

const writeFile = (notes) => {
  fs.writeFileSync('note-date.json', JSON.stringify(notes));
};

const addNote = (title, body) => {
  let notes = loadFile();

  const note = {
    title,
    body
  }


  console.log(notes);
  const duplicateArray = notes.filter((note) => note.title === title);

   console.log(duplicateArray);
  if(duplicateArray.length === 0){
    notes.push(note);
    writeFile(notes);
  }

};

The command line input is as follow:

node app.js add --title=Greeting --body="hello"
node app.js add --title=Greeting2 --body="hello2"

The output is:

[{"title":"Greeting","body":"hello"}]

The output should be:

[{"title":"Greeting","body":"hello"}, {"title":"Greeting2","body":"hello2"}]

My question is where this error occurs?

answered question

Try printing the error in catch block?

FYI doing [JSON.parse(stringData)] is going to continually wrap your data into a new array each time it is loaded even though you are saving it as an array already, meaning its going to do this: [], [[]],[[[]]],[[[[]]]]

1 Answer

12

Typo?

fs.writeFileSync('note-date.json', JSON.stringify(notes));

Isn't the file 'note-data.json'?

posted this

Have an answer?

JD

Please login first before posting an answer.