Environment variable loading system that supports multiple file formats, fallback strategies, and comprehensive error handling. This system forms the core of env-cmd's file processing capabilities.
Primary function for loading environment variables from files with automatic format detection and fallback support.
/**
* Load environment variables from files with support for both env files and RC files
* @param options - Configuration for loading environment variables
* @returns Promise resolving to loaded environment variables
*/
function getEnvVars(options?: GetEnvVarOptions): Promise<Environment>;
interface GetEnvVarOptions {
/** Configuration for .env file loading */
envFile?: EnvFileOptions;
/** Configuration for .env-cmdrc file loading */
rc?: RCFileOptions;
/** Enable verbose logging output */
verbose?: boolean;
}
interface EnvFileOptions {
/** Path to the environment file */
filePath?: string;
/** Whether to fall back to default locations if specified file not found */
fallback?: boolean;
}
interface RCFileOptions {
/** List of environment names to extract from RC file */
environments: string[];
/** Path to the RC file */
filePath?: string;
}Usage Examples:
// Via main package (GetEnvVars is an alias for getEnvVars)
import { GetEnvVars } from "env-cmd";
// Or via direct submodule import
import { getEnvVars } from "env-cmd/dist/get-env-vars.js";
// Load from default .env file locations (using GetEnvVars alias)
const env = await GetEnvVars();
// Load from specific env file
const env = await GetEnvVars({
envFile: { filePath: ".env.production" },
verbose: true
});
// Load from RC file with specific environments
const env = await GetEnvVars({
rc: {
environments: ["development", "staging"],
filePath: ".env-cmdrc"
}
});
// Load with fallback enabled
const env = await GetEnvVars({
envFile: {
filePath: "./config/.env",
fallback: true
}
});Function specifically for loading standard environment files (.env, .env.json, .env.js, etc.).
/**
* Load environment variables from .env format files
* @param options - Configuration for env file loading
* @returns Promise resolving to environment variables
*/
function getEnvFile(
{ filePath, fallback, verbose }: { filePath?: string, fallback?: boolean, verbose?: boolean },
): Promise<Environment>;Default File Locations:
./.env./.env.js./.env.jsonFile Resolution Process:
Function for loading multi-environment configuration files (.env-cmdrc format).
/**
* Load environment variables from .env-cmdrc format files
* @param options - Configuration for RC file loading
* @returns Promise resolving to environment variables
*/
function getRCFile(
{ environments, filePath, verbose }: { environments: string[], filePath?: string, verbose?: boolean },
): Promise<Environment>;Default RC File Locations:
./.env-cmdrc./.env-cmdrc.js./.env-cmdrc.jsonRC File Format:
{
"development": {
"NODE_ENV": "development",
"API_URL": "http://localhost:3000"
},
"production": {
"NODE_ENV": "production",
"API_URL": "https://api.production.com"
}
}Direct file parsing functions for specific file formats.
/**
* Parse environment variables from a specific file path
* @param envFilePath - Path to the environment file
* @returns Promise resolving to parsed environment variables
*/
function getEnvFileVars(envFilePath: string): Promise<Environment>;
/**
* Parse environment variables from RC file with specific environments
* @param options - RC file configuration
* @returns Promise resolving to merged environment variables
*/
function getRCFileVars(
{ environments, filePath }: { environments: string[], filePath: string },
): Promise<Environment>;The environment loading system supports the following file extensions:
const IMPORT_HOOK_EXTENSIONS = [
'.json',
'.js',
'.cjs',
'.mjs',
'.ts',
'.mts',
'.cts',
'.tsx',
];File Type Handling:
The loading system provides comprehensive error handling with specific error types:
interface PathError extends Error {
name: 'PathError';
}
interface EnvironmentError extends Error {
name: 'EnvironmentError';
}
interface ParseError extends Error {
name: 'ParseError';
}PathError: Thrown when files cannot be found
// File not found at specified path
const pathError = new Error(`Invalid env file path (${envFilePath}).`);
pathError.name = 'PathError';
throw pathError;EnvironmentError: Thrown when specified environments don't exist in RC files
// Environment not found in RC file
const envError = new Error(`Failed to find environments: [${environments.join(',')}]`);
envError.name = 'EnvironmentError';
throw envError;ParseError: Thrown when file parsing fails
// File exists but cannot be parsed
const parseError = new Error(`Failed to parse file: ${filePath}`);
parseError.name = 'ParseError';
throw parseError;When verbose mode is enabled, the loading system provides detailed logging:
// Success messages
console.info(`Found .env file at path: ${filePath}`);
console.info(`Found environments: [${environments.join(',')}] for .rc file at path: ${filePath}`);
// Failure messages
console.info(`Failed to find .env file at path: ${filePath}`);
console.info(`Failed to find environments: [${environments.join(',')}] for .rc file at path: ${filePath}`);Path resolution includes home directory expansion and absolute path conversion:
/**
* Resolve file paths with home directory expansion
* @param userPath - User-provided file path (may include ~)
* @returns Absolute resolved path
*/
function resolveEnvFilePath(userPath: string): string;Resolution Features:
~/config/.env → /home/user/config/.env./config/.env → /current/dir/config/.env/absolute/path/.env → /absolute/path/.env