diff --git a/.gitignore b/.gitignore index d8421de..893cde7 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ dist/ !.env.example *.log .DS_Store +.idea/ diff --git a/package.json b/package.json index a3698f3..86c686a 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "scripts": { "dev": "tsx watch src/index.ts", "build": "tsc", - "start": "node dist/index.js", + "start": "node --env-file=.env dist/index.js", "test": "vitest run", "typecheck": "tsc --noEmit" }, diff --git a/src/index.ts b/src/index.ts index ca6093f..938aa64 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 { 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({ logger: { level: "info",