52 lines
1.1 KiB
JavaScript
52 lines
1.1 KiB
JavaScript
import { readFileSync } from "node:fs";
|
|
import path from "node:path";
|
|
|
|
export function loadEnvFiles({
|
|
cwd = process.cwd(),
|
|
files = [".env", ".env.local"],
|
|
override = false,
|
|
} = {}) {
|
|
const originalKeys = new Set(Object.keys(process.env));
|
|
|
|
for (const fileName of files) {
|
|
const filePath = path.join(cwd, fileName);
|
|
|
|
try {
|
|
const source = readFileSync(filePath, "utf8");
|
|
applyEnvSource(source, { override, originalKeys });
|
|
} catch {
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
|
|
function applyEnvSource(source, { override, originalKeys }) {
|
|
for (const line of source.split(/\r?\n/)) {
|
|
const trimmedLine = line.trim();
|
|
|
|
if (!trimmedLine || trimmedLine.startsWith("#")) {
|
|
continue;
|
|
}
|
|
|
|
const separatorIndex = trimmedLine.indexOf("=");
|
|
|
|
if (separatorIndex === -1) {
|
|
continue;
|
|
}
|
|
|
|
const key = trimmedLine.slice(0, separatorIndex).trim();
|
|
const rawValue = trimmedLine.slice(separatorIndex + 1).trim();
|
|
const value = rawValue.replace(/^['"]|['"]$/g, "");
|
|
|
|
if (!key) {
|
|
continue;
|
|
}
|
|
|
|
if (!override && originalKeys.has(key)) {
|
|
continue;
|
|
}
|
|
|
|
process.env[key] = value;
|
|
}
|
|
}
|