process.env Reads Config With Defaults
Read environment variables with string-aware defaults: coalesce missing vars, coerce numbers explicitly, and parse flag or list values safely.
Code
// Write a variable the way a shell or test harness would, then read it back.
process.env.DEPLOY_ENV = 'staging';
const env = process.env.DEPLOY_ENV ?? 'development';
const port = Number(process.env.PORT ?? 3000);
const debug = process.env.DEBUG === 'on';
const tags = (process.env.DEPLOY_TAGS ?? '').split(',').filter(Boolean);
console.log('env:', env);
console.log('port:', port, typeof port === 'number');
console.log('debug flag:', debug);
console.log('tags:', tags.length);
// env values are always strings, so missing vars need explicit defaults
const unset = process.env.DEFINITELY_UNSET_VAR;
console.log('unset var is undefined:', unset === undefined);Output
Captured from a sandboxed run of this snippet in the build pipeline.
env: staging
port: 3000 true
debug flag: false
tags: 0
unset var is undefined: trueInside the snippet
The snippet is organized around the function tags.
Configuration comes from the environment — it reads DEPLOY_ENV, PORT, DEBUG, DEPLOY_TAGS, so the same code switches behavior between environments without edits.
What to watch for
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
Using it
The primary signature is const tags = (process.env.DEPLOY_TAGS ?? '')
Expect labeled output — env:, port:, debug flag: — when the file runs.
Key statements
const tags = (process.env.DEPLOY_TAGS ?? '').split(',').filter(Boolean);
const env = process.env.DEPLOY_ENV ?? 'development';
const port = Number(process.env.PORT ?? 3000);
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
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `tags` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.