MCPcopy
hub / github.com/toddbluhm/env-cmd / getEnvFileVars

Function getEnvFileVars

src/parse-env-file.ts:11–52  ·  view source on GitHub ↗
(envFilePath: string)

Source from the content-addressed store, hash-verified

9 * Gets the environment vars from an env file
10 */
11export async function getEnvFileVars(envFilePath: string): Promise<Environment> {
12 const absolutePath = resolveEnvFilePath(envFilePath)
13 if (!existsSync(absolutePath)) {
14 const pathError = new Error(`Invalid env file path (${envFilePath}).`)
15 pathError.name = 'PathError'
16 throw pathError
17 }
18
19 // Get the file extension
20 const ext = extname(absolutePath).toLowerCase()
21 let env: unknown;
22 if (IMPORT_HOOK_EXTENSIONS.includes(ext)) {
23 if (/tsx?$/.test(ext)) checkIfTypescriptSupported();
24
25 // For some reason in ES Modules, only JSON file types need to be specifically delinated when importing them
26 let attributeTypes = {}
27 if (ext === '.json') {
28 attributeTypes = { with: { type: 'json' } }
29 }
30 const res: unknown = await import(pathToFileURL(absolutePath).href, attributeTypes)
31 if (typeof res === 'object' && res && 'default' in res) {
32 env = res.default
33 } else {
34 env = res
35 }
36 // Check to see if the imported value is a promise
37 if (isPromise(env)) {
38 env = await env
39 }
40
41 return normalizeEnvObject(env, absolutePath)
42 }
43
44 const file = readFileSync(absolutePath, { encoding: 'utf8' })
45
46 switch (ext) {
47 // other loaders can be added here
48
49 default:
50 return parseEnvString(file)
51 }
52}
53
54/**
55 * Parse out all env vars from a given env file string and return an object

Callers 2

getEnvFileFunction · 0.85

Calls 5

resolveEnvFilePathFunction · 0.85
isPromiseFunction · 0.85
normalizeEnvObjectFunction · 0.85
parseEnvStringFunction · 0.85

Tested by

no test coverage detected