ubiQ
ubiQ

Reputation: 803

nodejs fs.exists()

I'm trying to call fs.exists in a node script but I get the error:

TypeError: Object # has no method 'exists'

I've tried replacing fs.exists() with require('fs').exists and even require('path').exists (just in case), but neither of these even list the method exists() with my IDE. fs is declared at the top of my script as fs = require('fs'); and I've used it previously to read files.

How can I call exists()?

Upvotes: 32

Views: 70154

Answers (4)

Warren Parad
Warren Parad

Reputation: 4091

You should be using fs.stats or fs.access instead. From the node documentation, exists is deprecated (possibly removed.)

If you are trying to do more than check existence, the documentation says to use fs.open. For example:

fs.access('myfile', (err) => {
  if (!err) {
    console.log('myfile exists and I have access');
    return;
  }
  console.log('myfile does not exist or I do not have access');
});

And now with async promises being the norm you actually can wrap this:

import { access } from 'node:fs/promises';

try {
  await access('myfile');
  console.log('myfile exists and I have access');
} catch (error) {
  console.log('myfile does not exist or I do not have access');
}

(What's does node: mean in the import statement, the node prevents someone from hijacking your fs package and injecting malicious code into your application. Always use node: prefix when your runtime supports it).

Upvotes: 23

CertainPerformance
CertainPerformance

Reputation: 371029

As others have pointed out, fs.exists is deprecated, in part because it uses a single (success: boolean) parameter instead of the much more common (error, result) parameters present nearly everywhere else.

However, fs.existsSync is not deprecated (because it doesn't use a callback, it just returns a value), and if the whole rest of your script depends on checking the existence of a single file, it can make things easier than having to deal with callbacks or surrounding the call with try/catch (in the case of accessSync):

const fs = require('fs');
if (fs.existsSync(path)) {
  // It exists
} else {
  // It doesn't exist
}

Of course, existsSync is synchronous and blocking. While this can sometimes be handy, if you need to do other operations in parallel (such as checking for the existence of multiple files at once), you should use one one of the other callback-based methods.

Modern versions of Node also support promise-based versions of fs methods, which one might prefer over callbacks:

fs.promises.access(path)
  .then(() => {
    // It exists
  })
  .catch(() => {
    // It doesn't exist
  });

Upvotes: 7

Scott Stensland
Scott Stensland

Reputation: 28305

Do NOT use fs.exists please read its API doc for alternative

this is the suggested alternative : go ahead and open file then handle error if any :

var fs = require('fs');

var cb_done_open_file = function(interesting_file, fd) {

    console.log("Done opening file : " + interesting_file);

    // we know the file exists and is readable
    // now do something interesting with given file handle
};

// ------------ open file -------------------- //

// var interesting_file = "/tmp/aaa"; // does not exist
var interesting_file = "/some/cool_file";

var open_flags = "r";

fs.open(interesting_file, open_flags, function(error, fd) {

    if (error) {

        // either file does not exist or simply is not readable
        throw new Error("ERROR - failed to open file : " + interesting_file);
    }

    cb_done_open_file(interesting_file, fd);
});

Upvotes: 6

lostsource
lostsource

Reputation: 21840

Your require statement may be incorrect, make sure you have the following

var fs = require("fs");

fs.exists("/path/to/file",function(exists){
  // handle result
});

Read the documentation here

http://nodejs.org/api/fs.html#fs_fs_exists_path_callback

Upvotes: 27

Related Questions