process.loadEnvFile Reads .env Natively

Load .env configuration with process.loadEnvFile() and note the precedence rule: values already in the environment are never overridden.

JavascriptConfig Management

Code

snippet
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: ENOENT

Under 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:fs is 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

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.