Skip to content
Env Reader
Language:en Author:AtomForge

Files and Directories

const certificate = env.file("TLS_CERT", "certs/server.pem");
const uploads = env.dir("UPLOAD_DIR", "var/uploads");

Both methods return an absolute path and perform a synchronous filesystem check.

file(key, defaultValue?, onMissing = true, stayInProject = true)
dir(key, defaultValue?, onMissing = true, stayInProject = true)

Resolution

The value is trimmed and resolved with path.resolve(projectRoot, value), regardless of stayInProject: a relative path always counts from the project root, an absolute path stays as it is. An empty value throws. The project root itself is normalized with path.resolve in the constructor.

  • stayInProject = true: the resolved path must lie inside the project root, both lexically and after resolving symlinks.
  • stayInProject = false: no boundary check; external absolute or ../ paths are allowed.
flowchart TD
    A[Variable or default] --> B[Trim and resolve against the project root]
    B --> C{stayInProject?}
    C -->|Yes| D[Check the project boundary]
    C -->|No| E[Filesystem check]
    D -->|Matches| E
    D -->|Does not match| F[Error]
    E --> G{Correct file or directory?}
    G -->|Yes| H[Return the path]
    G -->|No| I[Apply onMissing]

Missing or wrong-type paths

onMissing Behavior
true Throws an error; this is the default.
false Returns the path without creating anything.
(path) => void Calls the callback, then returns the path if the callback did not throw.

The callback may run both for a missing path and for a wrong type: for example, when a file is found where dir() is looking. There is no further type check after the callback.

import * as fs from "node:fs";

const cache = env.dir("CACHE_DIR", "var/cache", directory => {
    fs.mkdirSync(directory, { recursive: true });
});

Continue with Integration and Error Handling.

Teaches (2)

  • path resolution
  • filesystem checks