Node.js fs.readFile()

can anyone think of a reason for the readFile function's callback doesn't get executed?

fs.exists(filePath, function(exists){
   if(exists){ // results true
      fs.readFile(filePath, "utf8", function(err, data){
         if(err){
            console.log(err)
         }              
         console.log(data);
      })
   }
});

filePath is ./etc/coords.txt and it's a json formatted string.

using the Sync version - readFileSync - doesn't work as well.

Because the options is an object not a string:

fs.readFile(filename, [options], callback)

  • filename String
  • options Object
    • encoding String | Null default = null
    • flag String default = 'r'
  • callback Function

Asynchronously reads the entire contents of a file. Example:

fs.readFile('/etc/passwd', function (err, data) {   
    if (err) throw err;   console.log(data); 
  });

The callback is passed two arguments (err, data), where data is the contents of the file.

So:

fs.exists(filePath, function(exists){
   if(exists){ // results true
      fs.readFile(filePath, {encoding: "utf8"}, function(err, data){
         if(err){
            console.log(err)
         }              
         console.log(data);
      })
   }
});

I think it might be related to a problem with the text file. This file was generated by a C# app that wrote to the file a stream that contains Environment.NewLine Not sure that's it, anyway, once I have removed to Environment.NewLine it worked.