Check if a file or folder exists

Is there an API to check if a file or folder exists? I don’t see anything in the API.

// from the documentation it looks like I have call file.getEntry() and test for an error event or find a matching name

Test for error:

try {
	var entry = await folder.getEntry(filename);
	fileExists = true;
}
catch(fileError) {
	fileExists = false;
}

Test for matching name:

  try {

    subfolder = (await folder.getEntries()).find(entry => entry.name.includes(subfolderName));

    if (subfolder!=null) {
      return true;
    }
  }
  catch(error) {
    return false;
  }
1 Like

This seems to work:

/**
 * Returns true if a subfolder exists
 * @param {File} folder file of type folder  
 * @param {String} subfolderName name of sub folder
 * @returns {Boolean} returns true if folder exists
 */
async function checkSubFolderExists(folder, subfolderName) {
  var subfolder = null;

  try {
    subfolder = (await folder.getEntries()).find(entry => entry.name.includes(subfolderName));

    if (subfolder!=null && subfolder.isFolder) {
      return true;
    }
  }
  catch(fileError) {
    log(fileError);
  }

  return false;
}
1 Like

I am trying to get file/folder metadata. If that fails then I assume non-existence of that file/folder. Probably should be faster than listing all items in folder. But I would prefer built-in solution anyway.

1 Like

Yes. If you get an error the file doesn’t exist. You don’t have to loop through all the files. If you know the name of the file and already have a reference to the folder then you can use that.

It is very surprising that there is no fs.exists() and fs.existsSync() Node counterparts available.

So it seems we are stuck trying and catching errors for file existence. :cry:

On that note, does anyone know if the error code -4058 is reliable to indicate ONLY when a file or directory does not exist?

try {
  const data = await fs.readFile(
    filename,
    { encoding: 'utf-8' },
    null,
  );
} catch(error) {
  console.log('code: ' + error.code);
  console.log('message: ' + error.message);
}
code: -4058
message: "no such file or directory"

I don’t want to rely on it, if it can indicate other things.

1 Like

Update: I have come to discover that the error code is not reliable to indicate no such file or directory as it seems to be platform dependent. For example, on Windows it throws error code -4058 and on Mac it throws error code -2. For this reason I’ve decided to compare on the error.message value and not the error.code value in my catch block.

2 Likes