UNPKG

@foal/core

Version:

Full-featured Node.js framework, with no complexity

57 lines (56 loc) 1.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Env = void 0; const fs_1 = require("fs"); class Env { /** * Clear the cache of the loaded file .env (if it exists). * * @static * @memberof Config */ static clearCache() { this.dotEnv = null; } static getEnvironmentName() { return process.env.FOAL_ENV || process.env.NODE_ENV || 'development'; } static get(key) { if (process.env[key] !== undefined) { return process.env[key]; } if (this.dotEnv === null) { this.dotEnv = {}; this.loadEnv('.env'); this.loadEnv('.env.local'); this.loadEnv(`.env.${this.getEnvironmentName()}`); this.loadEnv(`.env.${this.getEnvironmentName()}.local`); } return this.dotEnv[key]; } static dotEnv = null; static loadEnv(filename) { if (!(0, fs_1.existsSync)(filename)) { return; } if (this.dotEnv === null) { this.dotEnv = {}; } const envFileContent = (0, fs_1.readFileSync)(filename, 'utf8'); for (const line of envFileContent.split('\n')) { if (line.startsWith('#')) { continue; } const [key, ...values] = line.split('='); const value = values.join('=').trim(); const trimmedKey = key.trim(); if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith('\'') && value.endsWith('\''))) { this.dotEnv[trimmedKey] = value.substr(1, value.length - 2); continue; } this.dotEnv[trimmedKey] = value; } } } exports.Env = Env;