Redon

一心的小屋

Node 提取 env 环境变量

发布于 # Node # typescript

验证方法

// 验证并提取环境变量
const getEnvVariable = (key: string): string | undefined => {
  const value = process.env[key];
  if (value === undefined) {
    return null;
  }
  return value;
};

// 将环境变量转换为数值
const getNumericEnvVariable = (key: string, defaultValue: number): number => {
  const value = getEnvVariable(key) ?? String(defaultValue);
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    return defaultValue;
  }
  return parsedValue;
};

// 将环境变量转换为布尔值
const getBooleanEnvVariable = (key: string, defaultValue: boolean): boolean => {
  const value = getEnvVariable(key) ?? String(defaultValue);
  return value.toLowerCase() === "true";
};

config 使用示例

import "dotenv/config";

export type Config = {
  PORT: number;
  ALLOWED_DOMAIN: string;
  USE_LOG: boolean;
};

export const config: Config = {
  PORT: getNumericEnvVariable("PORT", 3000),
  ALLOWED_DOMAIN: getEnvVariable("ALLOWED_DOMAIN") || "*",
  USE_LOG: getBooleanEnvVariable("USE_LOG", true),
};