37 lines
1.2 KiB
JavaScript
37 lines
1.2 KiB
JavaScript
// 单独拉起后端(不开桌面端):npm run backend
|
||
// 端口取环境变量 API_PORT,其次 .env 里的 API_PORT,默认 8788。
|
||
const { spawn } = require("child_process");
|
||
const path = require("path");
|
||
const fs = require("fs");
|
||
|
||
const root = path.join(__dirname, "..");
|
||
|
||
function readEnvFile(file) {
|
||
const values = {};
|
||
if (!fs.existsSync(file)) return values;
|
||
for (const line of fs.readFileSync(file, "utf8").split(/\r?\n/)) {
|
||
const trimmed = line.trim();
|
||
if (!trimmed || trimmed.startsWith("#")) continue;
|
||
const eq = trimmed.indexOf("=");
|
||
if (eq <= 0) continue;
|
||
values[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim();
|
||
}
|
||
return values;
|
||
}
|
||
|
||
const envFile = readEnvFile(path.join(root, ".env"));
|
||
const port = process.env.API_PORT || envFile.API_PORT || "8788";
|
||
|
||
const venvPy =
|
||
process.platform === "win32"
|
||
? path.join(root, ".venv", "Scripts", "python.exe")
|
||
: path.join(root, ".venv", "bin", "python");
|
||
const py = fs.existsSync(venvPy) ? venvPy : process.platform === "win32" ? "python" : "python3";
|
||
|
||
const child = spawn(py, ["backend/main.py"], {
|
||
cwd: root,
|
||
stdio: "inherit",
|
||
env: { ...process.env, PYTHONUTF8: "1", API_PORT: port },
|
||
});
|
||
child.on("exit", (code) => process.exit(code ?? 0));
|