env-file.js
846 Bytes
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import dotenv from 'dotenv'
import { devMysqlUrl } from '@drama/db'
const appRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
/**
* 数据库命令读取 `--env <file>`(默认 apps/voko-server/.env)里的 DATABASE_URL;
* 文件不存在或未设置时使用本地开发库 voko。
* @param {string[]} args
*/
export function databaseUrlFromArgs(args) {
const envIndex = args.indexOf('--env')
const file = envIndex === -1 ? path.join(appRoot, '.env') : path.resolve(args[envIndex + 1])
if (envIndex !== -1 && !fs.existsSync(file)) throw new Error(`--env file not found: ${file}`)
const env = fs.existsSync(file) ? dotenv.parse(fs.readFileSync(file)) : {}
return env.DATABASE_URL || devMysqlUrl('voko')
}