28 lines
917 B
JavaScript
28 lines
917 B
JavaScript
/**
|
|
* env.mjs — Load .env file if present
|
|
* Reads key=value pairs from .env and sets process.env for any missing vars.
|
|
* Never overwrites vars already set in the environment.
|
|
*/
|
|
import { existsSync, readFileSync } from 'fs';
|
|
import { resolve, dirname } from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const __dir = dirname(fileURLToPath(import.meta.url));
|
|
const envPath = resolve(__dir, '../.env');
|
|
|
|
export function loadEnv() {
|
|
if (!existsSync(envPath)) return;
|
|
const lines = readFileSync(envPath, 'utf8').split('\n');
|
|
for (const line of lines) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
const eq = trimmed.indexOf('=');
|
|
if (eq === -1) continue;
|
|
const key = trimmed.slice(0, eq).trim();
|
|
const val = trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, '');
|
|
if (key && !(key in process.env)) {
|
|
process.env[key] = val;
|
|
}
|
|
}
|
|
}
|