programming.protips.wiki
githubtwitter

Don't check if a file exists before reading it

#file-system #error-handling #race-condition

Don't check if a file exists before reading it - just read it, and use a try/catch block to handle the case where the file doesn't exist.

Bad Example

function getConfig(configPath) {
  if (!fs.existsSync(configPath)) {
    throw new Error(`Could not read config. Expected ${configPath} to exist`);
  }

  return fs.readFileSync(configPath, 'utf8');
}

Prefer

function getConfig(configPath) {
  try {
    return fs.readFileSync(configPath, 'utf8');
  } catch (e) {
    throw new AggregateError([`Could not read config file: ${configPath}`, e]);
  }
}

Why?

The second example protects against race conditions causing a bug. It's possible that the file could appear/disappear in between checking the existance of the file and reading it.

This general coding style is known as "Easier to ask for forgiveness than permission" (EAFP).

Further reading