import { readFileSync } from "fs"; import { join } from "path"; import { findUpSync } from "find-up"; import * as dotenv from "dotenv"; import { DefaultEnvFilesToRead } from "./constants"; import { getFormattedError } from "./utils/errror"; const getRoot = function isProjectRoot() { const root = findUpSync("resocket.json"); //do with node_modules? if (!root) throw new Error( getFormattedError({ coreMessage: "Unable to locate resocket.json file", humanMessage: "You can add a resocket.json file at the root of your project~", }) ); return root; }; export const readEnv = ( envFiles: string[] = DefaultEnvFilesToRead ): Record => { let filesToRead = envFiles; const rootDir = join(getRoot(), ".."); const filePaths: Array = []; for (let file of filesToRead) { const filePath = findUpSync(file, { stopAt: rootDir }); if (filePath) filePaths.push(filePath); } if (filePaths.length < 1) return {}; let envs = {}; for (let filePath of filePaths) { envs = { ...envs, ...dotenv.parse(readFileSync(filePath, "utf8")) }; } return envs; };