UNPKG

@adonisjs/env

Version:

Environment variable manager for Node.js

75 lines (74 loc) 2.21 kB
import { debuglog } from "node:util"; import { readFile } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import { isAbsolute, join } from "node:path"; var debug_default = debuglog("adonisjs:env"); var EnvLoader = class { #appRoot; #loadExampleFile; constructor(appRoot, loadExampleFile = false) { this.#appRoot = typeof appRoot === "string" ? appRoot : fileURLToPath(appRoot); this.#loadExampleFile = loadExampleFile; } async #loadFile(filePath) { try { return { contents: await readFile(filePath, "utf-8"), fileExists: true }; } catch (error) { /* c8 ignore next 3 */ if (error.code !== "ENOENT") throw error; return { contents: "", fileExists: false }; } } async load() { const ENV_PATH = process.env.ENV_PATH; const NODE_ENV = process.env.NODE_ENV; const envFiles = []; if (debug_default.enabled) { debug_default("ENV_PATH variable is %s", ENV_PATH ? "set" : "not set"); debug_default("NODE_ENV variable is %s", NODE_ENV ? "set" : "not set"); } const baseEnvPath = ENV_PATH ? isAbsolute(ENV_PATH) ? ENV_PATH : join(this.#appRoot, ENV_PATH) : this.#appRoot; if (debug_default.enabled) debug_default("dot-env files base path \"%s\"", baseEnvPath); if (NODE_ENV) { const nodeEnvLocalFile = join(baseEnvPath, `.env.${NODE_ENV}.local`); envFiles.push({ path: nodeEnvLocalFile, ...await this.#loadFile(nodeEnvLocalFile) }); } if (!NODE_ENV || !["test", "testing"].includes(NODE_ENV)) { const envLocalFile = join(baseEnvPath, ".env.local"); envFiles.push({ path: envLocalFile, ...await this.#loadFile(envLocalFile) }); } if (NODE_ENV) { const nodeEnvFile = join(baseEnvPath, `.env.${NODE_ENV}`); envFiles.push({ path: nodeEnvFile, ...await this.#loadFile(nodeEnvFile) }); } const envFile = join(baseEnvPath, ".env"); envFiles.push({ path: envFile, ...await this.#loadFile(envFile) }); if (this.#loadExampleFile) { const envExampleFile = join(baseEnvPath, ".env.example"); envFiles.push({ path: envExampleFile, ...await this.#loadFile(envExampleFile) }); } return envFiles; } }; export { debug_default as n, EnvLoader as t };