fix(lpt-ai):启动时未加载 .env 文件导致 LLM_API_KEY 始终为空
根因:项目未依赖 dotenv,启动脚本也未使用 --env-file, process.env 中没有 LLM_API_KEY,isAvailable() 始终返回 false, /health 端点返回 llmAvailable: false。 修复: - index.ts 启动时手动读取 .env 并注入 process.env (零依赖,兼容 tsx watch dev 和 node dist 两种启动方式) - start 脚本保留 node --env-file=.env 双保险 - .gitignore 加入 .idea/
This commit is contained in:
@@ -5,3 +5,4 @@ dist/
|
|||||||
!.env.example
|
!.env.example
|
||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.idea/
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "tsx watch src/index.ts",
|
"dev": "tsx watch src/index.ts",
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"start": "node dist/index.js",
|
"start": "node --env-file=.env dist/index.js",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,26 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { dirname, resolve } from "node:path";
|
||||||
import Fastify from "fastify";
|
import Fastify from "fastify";
|
||||||
import { aiRoutes } from "./routes/ai.js";
|
import { aiRoutes } from "./routes/ai.js";
|
||||||
|
|
||||||
|
// ===== 加载 .env(零依赖,兼容 dev/start 两种启动方式)=====
|
||||||
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const envPath = resolve(__dirname, "..", ".env");
|
||||||
|
try {
|
||||||
|
for (const line of readFileSync(envPath, "utf-8").split(/\r?\n/)) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (!trimmed || trimmed.startsWith("#")) continue;
|
||||||
|
const eq = trimmed.indexOf("=");
|
||||||
|
if (eq === -1) continue;
|
||||||
|
const k = trimmed.slice(0, eq).trim();
|
||||||
|
const v = trimmed.slice(eq + 1).trim();
|
||||||
|
if (k && !(k in process.env)) process.env[k] = v;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// .env not found, use system environment
|
||||||
|
}
|
||||||
|
|
||||||
const app = Fastify({
|
const app = Fastify({
|
||||||
logger: {
|
logger: {
|
||||||
level: "info",
|
level: "info",
|
||||||
|
|||||||
Reference in New Issue
Block a user