Files
mv2_simple_crx/server/config/env.js
张成 3d3b9b5dfa 1
2026-03-18 15:46:57 +08:00

75 lines
1.6 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
let loaded = false;
let env_map = {};
function unquote(value) {
const v = String(value);
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
return v.slice(1, -1);
}
return v;
}
function parse_env_text(text) {
const out = {};
const lines = String(text).split(/\r?\n/);
for (const raw_line of lines) {
const line = raw_line.trim();
if (!line) continue;
if (line.startsWith('#')) continue;
const idx = line.indexOf('=');
if (idx <= 0) continue;
const key = line.slice(0, idx).trim();
let value = line.slice(idx + 1).trim();
// 去掉行尾注释:仅在未被引号包裹时生效
const quoted = (value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"));
if (!quoted) {
const sharp = value.indexOf('#');
if (sharp >= 0) {
value = value.slice(0, sharp).trim();
}
}
out[key] = unquote(value);
}
return out;
}
export function load_env() {
if (loaded) {
return;
}
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const env_path = path.resolve(__dirname, '../.env');
const text = fs.readFileSync(env_path, 'utf8');
env_map = parse_env_text(text);
loaded = true;
}
export function get_env(key) {
if (!loaded) {
load_env();
}
return env_map[key];
}
export function get_all_env() {
if (!loaded) {
load_env();
}
return { ...env_map };
}
load_env();