Skip to content

Commit 6a86311

Browse files
committed
doc: clarify variable precedence in process.loadEnvFile()
Document that process.loadEnvFile() does not overwrite variables that already exist in process.env, including ones set by a previous call, and that this differs from multiple --env-file flags where later files win. Show how to override values using util.parseEnv(). Fixes: nodejs#66315
1 parent 66f26d3 commit 6a86311

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

‎doc/api/process.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2726,6 +2726,13 @@ changes:
27262726
Loads the `.env` file into `process.env`. Usage of `NODE_OPTIONS`
27272727
in the `.env` file will not have any effect on Node.js.
27282728
2729+
If a variable is already defined in `process.env`, its existing value takes
2730+
precedence and is not overwritten by the value from the file. This also applies
2731+
to variables set by a previous call to `process.loadEnvFile()`, so when loading
2732+
multiple files, the value from the first file that defines a variable is used.
2733+
This differs from passing multiple [`--env-file`][] flags, where values from
2734+
later files override those from earlier files.
2735+
27292736
```cjs
27302737
const { loadEnvFile } = require('node:process');
27312738
loadEnvFile();
@@ -2736,6 +2743,21 @@ import { loadEnvFile } from 'node:process';
27362743
loadEnvFile();
27372744
```
27382745
2746+
To override existing values, parse the file with [`util.parseEnv()`][] and
2747+
assign the result to `process.env`:
2748+
2749+
```cjs
2750+
const { readFileSync } = require('node:fs');
2751+
const { parseEnv } = require('node:util');
2752+
Object.assign(process.env, parseEnv(readFileSync('.env', 'utf8')));
2753+
```
2754+
2755+
```mjs
2756+
import { readFileSync } from 'node:fs';
2757+
import { parseEnv } from 'node:util';
2758+
Object.assign(process.env, parseEnv(readFileSync('.env', 'utf8')));
2759+
```
2760+
27392761
## `process.mainModule`
27402762
27412763
<!-- YAML
@@ -4632,6 +4654,7 @@ cases:
46324654
[`'exit'`]: #event-exit
46334655
[`'message'`]: child_process.md#event-message
46344656
[`'uncaughtException'`]: #event-uncaughtexception
4657+
[`--env-file`]: cli.md#--env-filefile
46354658
[`--no-deprecation`]: cli.md#--no-deprecation
46364659
[`--permission-audit`]: cli.md#--permission-audit
46374660
[`--permission`]: cli.md#--permission
@@ -4674,6 +4697,7 @@ cases:
46744697
[`require.cache`]: modules.md#requirecache
46754698
[`require.main`]: modules.md#accessing-the-main-module
46764699
[`subprocess.kill()`]: child_process.md#subprocesskillsignal
4700+
[`util.parseEnv()`]: util.md#utilparseenvcontent
46774701
[`v8.setFlagsFromString()`]: v8.md#v8setflagsfromstringflags
46784702
[built-in modules with mandatory `node:` prefix]: modules.md#built-in-modules-with-mandatory-node-prefix
46794703
[debugger]: debugger.md

0 commit comments

Comments
 (0)