process.loadEnvFile Reads .env Natively
Load .env configuration with process.loadEnvFile() and note the precedence rule: values already in the environment are never overridden.
Code
import { writeFileSync } from 'node:fs';
// .env is the de-facto config format; Node loads it natively, no package
writeFileSync('.env', 'PORT=4017\nLOG_LEVEL=debug\n');
process.loadEnvFile();
console.log('PORT =', process.env.PORT);
// values already present in the environment win over the .env file
process.env.LOG_LEVEL = 'info';
writeFileSync('.env', 'PORT=4017\nLOG_LEVEL=debug\n');
process.loadEnvFile();
console.log('LOG_LEVEL after reload =', process.env.LOG_LEVEL);
// loadEnvFile throws when the file is missing, unlike reading env directly
try {
process.loadEnvFile('missing.env');
} catch (err) {
console.log('missing file:', err.code);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
PORT = 4017LOG_LEVEL=debug
LOG_LEVEL after reload = info
missing file: ENOENTUnder the hood
writeFileSync comes from node:fs — Node.js core modules the runtime ships with.
Configuration comes from the environment — it reads PORT, LOG_LEVEL, so the same code switches behavior between environments without edits.
Watch out for
node:fsis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Using it
Output lines are prefixed (PORT =, LOG_LEVEL after reload =, missing file:), so each step’s effect stands out.
Key statements
writeFileSync('.env', 'PORT=4017\nLOG_LEVEL=debug\n');
process.loadEnvFile('missing.env');
process.env.LOG_LEVEL = 'info';
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
- Is the imported module an npm package?
- No — `node:fs` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.
Report a problem with this exampleOpens a pre-filled issue on GitHub.