diff --git a/doc/api/cli.md b/doc/api/cli.md index 80f2fa74818b92..7f4b7025583280 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -937,6 +937,26 @@ changes: Behavior is the same as [`--env-file`][], but an error is not thrown if the file does not exist. +### `--env-file-override-local` + + + +By default, when a variable defined in an env file is already set in the +environment, the existing value is preserved. Pass +`--env-file-override-local` together with [`--env-file`][] (or +[`--env-file-if-exists`][]) to make values from the file override existing +environment variables instead. + +```bash +BASIC=local node --env-file=.env --env-file-override-local -p 'process.env.BASIC' +# prints the value from .env, not 'local'. +``` + +To override variables at runtime, use the `override` option of +[`process.loadEnvFile()`][]. + ### `--env-file=file` -* `path` {string | URL | Buffer | undefined}. **Default:** `'./.env'` +* `path` {string | URL | Buffer | undefined} **Default:** `'./.env'` +* `options` {Object} + * `override` {boolean} If `true`, values from the file replace any matching + variable already set in `process.env`. **Default:** `false`. Loads the `.env` file into `process.env`. Usage of `NODE_OPTIONS` in the `.env` file will not have any effect on Node.js. @@ -2782,6 +2785,38 @@ import { loadEnvFile } from 'node:process'; loadEnvFile(); ``` +By default, an env file does not override variables that are already set. +Pass `override: true` to replace them with the values from the file: + +```cjs +const { loadEnvFile } = require('node:process'); +// process.env.API_KEY === 'local-key' +loadEnvFile('.env', { override: true }); +// process.env.API_KEY now matches the value from .env +``` + +```mjs +import { loadEnvFile } from 'node:process'; +// process.env.API_KEY === 'local-key' +loadEnvFile('.env', { override: true }); +// process.env.API_KEY now matches the value from .env +``` + +When called with options only, the default `'./.env'` path is used: + +```cjs +const { loadEnvFile } = require('node:process'); +loadEnvFile({ override: true }); +``` + +```mjs +import { loadEnvFile } from 'node:process'; +loadEnvFile({ override: true }); +``` + +The same behavior is available at startup via the +[`--env-file-override-local`][] flag. + ## `process.mainModule`