From 6059406991f62d137b97863d5050c14f3b72c4b4 Mon Sep 17 00:00:00 2001 From: Sepandar Derakhshandeh Date: Sun, 27 Sep 2026 11:15:07 +0330 Subject: [PATCH] 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: https://github.com/nodejs/node/issues/66315 Signed-off-by: Sepandar Derakhshandeh --- doc/api/process.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/doc/api/process.md b/doc/api/process.md index 8d0e4ae8d6fc..50b5c8298da4 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -2726,6 +2726,13 @@ changes: Loads the `.env` file into `process.env`. Usage of `NODE_OPTIONS` in the `.env` file will not have any effect on Node.js. +If a variable is already defined in `process.env`, its existing value takes +precedence and is not overwritten by the value from the file. This also applies +to variables set by a previous call to `process.loadEnvFile()`, so when loading +multiple files, the value from the first file that defines a variable is used. +This differs from passing multiple [`--env-file`][] flags, where values from +later files override those from earlier files. + ```cjs const { loadEnvFile } = require('node:process'); loadEnvFile(); @@ -2736,6 +2743,22 @@ import { loadEnvFile } from 'node:process'; loadEnvFile(); ``` +To override existing values, parse the file with [`util.parseEnv()`][] and +assign the result to `process.env`: + +```cjs +const { readFileSync } = require('node:fs'); +const { parseEnv } = require('node:util'); +Object.assign(process.env, parseEnv(readFileSync('.env', 'utf8'))); +``` + +```mjs +import process from 'node:process'; +import { readFileSync } from 'node:fs'; +import { parseEnv } from 'node:util'; +Object.assign(process.env, parseEnv(readFileSync('.env', 'utf8'))); +``` + ## `process.mainModule`