Env Config Precedence Resolver
Resolve configuration from defaults file environment and CLI args with explicit precedence and type coercion.
Code
export function resolveConfig({defaults={},file={},env=process.env,args={}}={}){const merged={};for(const[key,defaultVal]of Object.entries(defaults)){const raw=args[key]??env[key.toUpperCase()]??file[key]??defaultVal;merged[key]=coerce(raw,defaultVal);}return merged;}function coerce(value,ref){if(typeof ref==='number')return Number(value);if(typeof ref==='boolean')return value==='true'||value===true;if(typeof ref==='object'&&ref!==null)return JSON.parse(value);return String(value);}How the snippet works
The working surface is the functions resolveConfig and coerce — everything else is wiring.
What to watch for
- The guard
typeof ref==='number'short-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The primary signature is export function resolveConfig({defaults={},file={},env=process.env,args={}}={})
resolveConfig is the public entry point; everything else in the file exists to support it.
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `resolveConfig`, `coerce` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.