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`