UNPKG

@znode/config

Version:

Load config support .env, $ID.{yml,json,ini}

78 lines (77 loc) 2.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isRc = exports.isIni = exports.isToml = exports.isJSON = exports.isYml = exports.isDotEnv = exports.getConfigPath = exports.getConfigPaths = void 0; const os = require("os"); const path = require("path"); const fs = require("@znode/fs"); const dirs = [ process.cwd(), path.resolve(os.homedir(), '.config'), os.homedir(), path.resolve('/configs'), path.resolve('/opt/configs'), // zmicro mac ]; async function getConfigPaths(id, options) { const projectPath = options === null || options === void 0 ? void 0 : options.projectPath; const filenames = id ? [`${id}.yml`, `${id}.json`, `${id}.toml`, `${id}.ini`, `.${id}rc`] : ['.env']; const filepaths = []; for (const filename of filenames) { const isNoneDotStart = !/^\./.test(filename); if (projectPath) { filepaths.push(path.resolve(projectPath, filename)); if (isNoneDotStart) { filepaths.push(path.resolve(projectPath, `.${filename}`)); } } else { for (const dir of dirs) { filepaths.push(path.resolve(dir, filename)); if (isNoneDotStart) { filepaths.push(path.resolve(dir, `.${filename}`)); } } } } return filepaths; } exports.getConfigPaths = getConfigPaths; async function getConfigPath(id, options) { const filepaths = await getConfigPaths(id, options); for (const filepath of filepaths) { if (await fs.exist(filepath)) { return filepath; } } // if (!id) { throw new Error(`Cannot found config .env`); } throw new Error(`Cannot found config for ${id}`); } exports.getConfigPath = getConfigPath; function isDotEnv(filepath) { return /\.env$/.test(filepath); } exports.isDotEnv = isDotEnv; function isYml(filepath) { return /\.(yml|yaml)$/.test(filepath); } exports.isYml = isYml; function isJSON(filepath) { return /\.json$/.test(filepath); } exports.isJSON = isJSON; function isToml(filepath) { return /\.toml$/.test(filepath); } exports.isToml = isToml; function isIni(filepath) { return /\.ini$/.test(filepath); } exports.isIni = isIni; function isRc(filepath) { return /\.\w+rc$/.test(filepath); } exports.isRc = isRc;