1

I would like to console.log a message and return an empty array if I try to read a file that doesn't exist. The getAllNotes function fires effective and the error is definitely thrown no such file or directory, open 'notes.json'.

However, why is the error thrown if I didn't specify throw err in my if statement? Secondly why doesn't my console.log message get outputted and the empty array not returned?

var getAllNotes = () => {
  console.log("MADE IT TO GET ALL NOTES")
  var notesArray = fs.readFileSync('notes.json', (err, data) => {
    if (err) {
      console.log("There are no notes to display");
      return [];
    } else {
      console.log("DATA",data)
      console.log("MADE IT TO PARSE")
      return JSON.parse(data);
    }
  });
  console.log("INSIDE GET ALL NOTES", notesArray)
};

1 Answer 1

2

fs.readFileSync is a blocking call and doesn't take a callback in the same way that fs.readFile does. It simply returns the contents of the file, see the below example:

var fs = require('fs');
var date = fs.readFileSync('myfile', 'utf8');
console.log(data);

When I ran your example an exception is thrown because you are providing a callback function where it is expecting a string or object for the options parameter.

You can do a blocking call with fs.existsSync(path) to check if the file exists before trying to read it.

Alternatively you can use the non-blocking version of the readFile and provide the callback as you were trying to do.

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

2 Comments

Oh my goodness. That fixed the problem. What a great learning opportunity... I would really like to know how you determined from reading the error message that it was expecting a string or object from the options parameter because I am rereading those errors and all I can take away is that the file I am trying to read doesn't exist.
So all I did was copy your example, add the require for fs and add a line to call your getAllNotes(). When I then ran this with nodejs I got this exception: TypeError: Expected options to be either an object or a string, but got function instead. Are you running it in the same way?

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.