starraid/star-raid/server/env.js

33 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use strict";
/* ================= .env 配置加载(零依赖) =================
启动时最先加载:读取 star-raid/.env注入 process.env。
约定:真实环境变量优先(已存在的不覆盖),.env 仅作默认。 */
const fs = require("node:fs");
const path = require("node:path");
const ENV_PATH = path.join(__dirname, "..", ".env");
if (fs.existsSync(ENV_PATH)) {
for (const line of fs.readFileSync(ENV_PATH, "utf8").split(/\r?\n/)) {
const s = line.trim();
if (!s || s.startsWith("#")) continue;
const i = s.indexOf("=");
if (i <= 0) continue;
const key = s.slice(0, i).trim();
let val = s.slice(i + 1).trim();
// 去掉成对引号
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'")))
val = val.slice(1, -1);
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && process.env[key] === undefined)
process.env[key] = val;
}
}
/* 路径展开:支持 ~ 开头 */
function expandHome(p) {
if (p === "~") return require("node:os").homedir();
if (p && p.startsWith("~/")) return require("node:os").homedir() + p.slice(1);
return p;
}
module.exports = { expandHome };