@anyme/anymejs
Version:
46 lines (44 loc) • 1.8 kB
JavaScript
import { existsSync, readFileSync } from 'node:fs';
import { isAbsolute, resolve } from 'node:path';
(function env(path) {
const parse = (path) => {
const envContent = readFileSync(path, "utf8").replace(/^\uFEFF/, "");
const lines = envContent.split(/\r?\n/);
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine || trimmedLine.startsWith("#"))
continue;
const sepIndex = trimmedLine.indexOf("=");
if (sepIndex === -1)
continue;
const key = line.slice(0, sepIndex).trim();
if (!key)
continue;
let value = trimmedLine.slice(sepIndex + 1).trim();
const commentIndex = value.indexOf("#");
if (commentIndex !== -1)
value = value.slice(0, commentIndex).trim();
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
const quoteChar = value[0];
value = value.slice(1, -1);
if (quoteChar === '"') {
value = value.replace(/\\"/g, '"').replace(/\\\\/g, "\\");
}
else {
value = value.replace(/\\'/g, "'").replace(/\\\\/g, "\\");
}
}
if (typeof process !== "undefined" && !(key in process.env))
process.env[key] = value;
}
};
const absolutePath = isAbsolute(path) ? path : resolve(path);
if (!existsSync(absolutePath))
return;
if (typeof process?.loadEnvFile === "function")
process.loadEnvFile(absolutePath);
else
parse(absolutePath);
})(".env");
//# sourceMappingURL=env.js.map