env.ts
727 B · typescript · 23 lines
1import { existsSync, readFileSync } from "node:fs";2import { join, resolve } from "node:path";34const DESK = resolve(import.meta.dir, "../../..");56export function loadEnv(path = join(DESK, ".env")) {7 if (!existsSync(path)) return;8 for (const line of readFileSync(path, "utf8").split("\n")) {9 const clean = line.trim();10 if (!clean || clean.startsWith("#")) continue;11 const at = clean.indexOf("=");12 if (at < 0) continue;13 const key = clean.slice(0, at).trim();14 if (process.env[key]) continue;15 process.env[key] = clean.slice(at + 1).trim();16 }17}1819export function need(key: string) {20 const value = process.env[key];21 if (!value) throw new Error(`site: ${key} is not in .env`);22 return value;23}