Regalamiunsorriso/faceai/tests/live-site/load-live-env.js

52 lines
No EOL
1.1 KiB
JavaScript

const fs = require('fs');
const path = require('path');
let loaded = false;
function parseEnvLine(line) {
const trimmed = String(line || '').trim();
if (!trimmed || trimmed.startsWith('#')) {
return null;
}
const separatorIndex = trimmed.indexOf('=');
if (separatorIndex <= 0) {
return null;
}
const key = trimmed.slice(0, separatorIndex).trim();
let value = trimmed.slice(separatorIndex + 1).trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
return { key, value };
}
function loadLiveEnv() {
if (loaded) {
return;
}
loaded = true;
const envPath = path.resolve(__dirname, '..', '..', '.env');
if (!fs.existsSync(envPath)) {
return;
}
const envText = fs.readFileSync(envPath, 'utf8');
for (const line of envText.split(/\r?\n/)) {
const entry = parseEnvLine(line);
if (!entry || !entry.key || Object.prototype.hasOwnProperty.call(process.env, entry.key)) {
continue;
}
process.env[entry.key] = entry.value;
}
}
module.exports = {
loadLiveEnv
};