Node.js

Handle a missing file by its error code

Attempt the read and handle ENOENT when a missing file has an expected fallback. Avoid a separate existence check, because the path can change between checking and reading.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
  const path = join(directory, "optional.txt");
  try {
    console.log(await fs.readFile(path, "utf8"));
  } catch (error) {
    if (error.code !== "ENOENT") throw error;
    console.log("Using defaults");
  }
} finally {
  await fs.rm(directory, {recursive: true, force: true});
}

How it works

The catch block only handles the known missing-path case and lets unrelated failures propagate. This keeps permission problems or storage errors from being silently reclassified as an absent optional configuration file.

Limits and mistakes

ENOENT can also describe a missing parent component. Make sure that absence is acceptable for the entire path in this workflow. Catching every error and returning defaults can conceal deployment mistakes that deserve immediate attention.

Check the result

Expect Using defaults. Create the file in a second run and confirm its contents are read. Keep a separate permission-error check where the operating system and test environment support it.

Sources

Reference documentation for the behavior used in this guide: