44 lines
1.5 KiB
JavaScript
44 lines
1.5 KiB
JavaScript
import { existsSync, readFileSync } from 'node:fs';
|
|
import { dirname, resolve } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
function parseEnvLine(line) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed || trimmed.startsWith('#'))
|
|
return null;
|
|
const equalsIndex = trimmed.indexOf('=');
|
|
if (equalsIndex === -1)
|
|
return null;
|
|
const key = trimmed.slice(0, equalsIndex).trim();
|
|
let value = trimmed.slice(equalsIndex + 1).trim();
|
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
|
|
return null;
|
|
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
(value.startsWith("'") && value.endsWith("'"))) {
|
|
value = value.slice(1, -1);
|
|
}
|
|
return { key, value };
|
|
}
|
|
function loadEnvFile(path) {
|
|
if (!existsSync(path))
|
|
return;
|
|
const content = readFileSync(path, 'utf8');
|
|
for (const line of content.split(/\r?\n/)) {
|
|
const parsed = parseEnvLine(line);
|
|
if (!parsed || process.env[parsed.key] !== undefined)
|
|
continue;
|
|
process.env[parsed.key] = parsed.value;
|
|
}
|
|
}
|
|
export function loadEnv() {
|
|
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
const candidatePaths = [
|
|
resolve(process.cwd(), '.env'),
|
|
resolve(process.cwd(), '..', '.env'),
|
|
resolve(moduleDir, '..', '.env'),
|
|
resolve(moduleDir, '..', '..', '.env')
|
|
];
|
|
for (const path of [...new Set(candidatePaths)]) {
|
|
loadEnvFile(path);
|
|
}
|
|
}
|
|
//# sourceMappingURL=loadEnv.js.map
|