Ulysses
Ulysses

Reputation: 6003

nodejs: Unable to read file contents

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.

Upvotes: 1

Views: 2471

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

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.

Upvotes: 3

Related Questions