1

I am trying to read the contents of a file. The file existence check passes, even then the file read excepts as shown below:

var fs = require('fs')
fs.exists('c:\\abc.txt',function(exists){
    console.log("exists");
    fs.readFile('c:\\abc.txt', 'UTF-8', function (err,data) {
            if (err) {
                console.log("err"+err);
            }            
            console.log("data:"+data);                
    });
});

Output

exists
errError: ENOENT: no such file or directory, open 'c:\abc.txt'
data:undefined

How may I correct this.

Ulysses
  • 5,616
  • 7
  • 48
  • 84
  • fs.exists is deprecated for years, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callback – baao May 05 '17 at 09:02
  • The backslash character cancels any "special meaning" the subsequent character has, so "\\" is read as simply "\", you would need to write "\\\\" in order to get "\\". That is why is says no file "c:\abc.txt" with only one backslash even though you typed two. – jeremye May 05 '17 at 09:03

1 Answers1

3

Your code isn't checking that the result from fs.exists is that the file exists. You're just going ahead with your file read in the callback. You need to check the first argument to see if it's true (the file exists) or false (it doesn't). Currently, your code isn't using the exists parameter at all. (It also should exit the readFile callback or otherwise skip the bit using data if err isn't null.)

But fs.exists has been deprecated for ages, and separately, there's no point in checking whether a file exists before trying to read it, since it can be created or deleted after the exists check but before the read. Just try to read the file, and handle the error if you can't:

var fs = require('fs');
fs.readFile('c:\\abc.txt', 'UTF-8', function(err, data) {
    if (err) {
        console.log("err"+err);
        return;
    }
    console.log("data:"+data);                
});

If you really want to check existence before reading, you could use fs.existsSync (which is not deprecated), which at least reduces the window between the check for existence and reading the file, but it really still doesn't make much sense.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks @TJ Crowder, although ".exists" works for now but its mentioned that its no longer supported by community and might be deprecated in higher versions. – Ulysses May 08 '17 at 03:19
  • @StillNestling: *"...might be deprecated in higher versions"* It's deprecated **now**, and has been for years. At some point it may well be removed. I've been following this saga [a while now](http://stackoverflow.com/questions/4482686/check-synchronously-if-file-directory-exists-in-node-js/4482701#4482701). I wouldn't suggest using deprecated APIs, particularly long-deprecated ones. – T.J. Crowder May 08 '17 at 06:29