Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -1367,6 +1367,9 @@ variables which configure Node.js][environment_variables], such as `NODE_OPTIONS
are parsed and applied. If the same variable is defined in the environment and
in the file, the value from the environment takes precedence.

The flag is only recognized before the script. Arguments after the script name
or after `--` are passed to the script and are not read as Node.js options.

You can pass multiple `--env-file` arguments. Subsequent files override
pre-existing variables defined in previous files.

Expand Down
46 changes: 1 addition & 45 deletions src/node_config_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,63 +8,19 @@

namespace node {

constexpr std::string_view kConfigFileFlag = "--config-file";
// TODO(marco-ippolito): Remove these aliases in a semver-major.
constexpr std::string_view kExperimentalConfigFileFlag =
"--experimental-config-file";
constexpr std::string_view kDefaultConfigFileFlag =
"--experimental-default-config-file";
constexpr std::string_view kDefaultConfigFileName = "node.config.json";
constexpr std::string_view kSchemaField = "$schema";

inline bool HasEqualsPrefix(std::string_view arg, std::string_view flag) {
return arg.size() > flag.size() && arg.starts_with(flag) &&
arg[flag.size()] == '=';
}

inline bool IsBareConfigFileFlag(std::string_view arg) {
return arg == kConfigFileFlag || arg == kExperimentalConfigFileFlag ||
arg == kDefaultConfigFileFlag;
}

inline bool IsConfigFileFlag(std::string_view arg) {
return IsBareConfigFileFlag(arg) || HasEqualsPrefix(arg, kConfigFileFlag) ||
HasEqualsPrefix(arg, kExperimentalConfigFileFlag) ||
HasEqualsPrefix(arg, kDefaultConfigFileFlag);
}

inline std::string DefaultConfigFileArg() {
return std::string(kConfigFileFlag) + "=" +
std::string(kDefaultConfigFileName);
}

// Returns the index of the first entry in `args` that is neither the program
// name nor an option for Node.js itself. Everything from there on is the
// script and its arguments, or follows `--`, so it must not be read as a
// config file flag.
size_t GetNodeOptionsEnd(const std::vector<std::string>& args) {
// The bare flags take no value. Spell them out the way GetDataFromArgs()
// does before the real parse, otherwise the parser would consume the next
// argument as the path.
std::vector<std::string> remaining;
remaining.reserve(args.size());
for (const std::string& arg : args) {
remaining.push_back(IsBareConfigFileFlag(arg) ? DefaultConfigFileArg()
: arg);
}

// Parsing into throwaway options stops exactly where the real parse will.
// Any errors are reported by the real parse later on.
PerProcessOptions options;
std::vector<std::string> v8_args;
std::vector<std::string> errors;
options_parser::Parse(
&remaining, nullptr, &v8_args, &options, kDisallowedInEnvvar, &errors);

// `remaining` is left with the program name and the unparsed arguments.
return args.size() - remaining.size() + 1;
}

std::optional<std::string_view> ConfigReader::GetDataFromArgs(
std::vector<std::string>* args) {
std::optional<std::string_view> result;
Expand All @@ -75,7 +31,7 @@ std::optional<std::string_view> ConfigReader::GetDataFromArgs(
return result;
}

const size_t node_options_end = GetNodeOptionsEnd(*args);
const size_t node_options_end = options_parser::GetNodeOptionsEnd(*args);
for (size_t i = 1; i < node_options_end; ++i) {
std::string& arg = (*args)[i];

Expand Down
32 changes: 24 additions & 8 deletions src/node_dotenv.cc
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#include "node_dotenv.h"
#include <algorithm>
#include <unordered_set>
#include "env-inl.h"
#include "node_file.h"
#include "node_options.h"
#include "uv.h"

namespace node {
Expand All @@ -22,17 +24,31 @@ std::vector<Dotenv::env_file_data> Dotenv::GetDataFromArgs(
const std::vector<std::string>& args) {
const std::string_view optional_env_file_flag = "--env-file-if-exists";

const auto find_match = [](const std::string& arg) {
return arg == "--" || arg == "--env-file" ||
arg.starts_with("--env-file=") || arg == "--env-file-if-exists" ||
const auto is_env_file_flag = [](const std::string& arg) {
return arg == "--env-file" || arg.starts_with("--env-file=") ||
arg == "--env-file-if-exists" ||
arg.starts_with("--env-file-if-exists=");
};
const auto find_match = [&](const std::string& arg) {
return arg == "--" || is_env_file_flag(arg);
};

std::vector<Dotenv::env_file_data> env_files;
// This will be an iterator, pointing to args.end() if no matches are found
auto matched_arg = std::ranges::find_if(args, find_match);
// Only pay for the extra parse when an env file flag might be present.
if (args.empty() ||
std::none_of(args.begin(), args.end(), is_env_file_flag)) {
return env_files;
}

// Only the options of Node.js itself are considered. The script and its
// arguments are left alone.
const auto options_begin = args.begin() + 1;
const auto options_end =
args.begin() + options_parser::GetNodeOptionsEnd(args);
// This will be an iterator, pointing to options_end if no matches are found
auto matched_arg = std::find_if(options_begin, options_end, find_match);

while (matched_arg != args.end()) {
while (matched_arg != options_end) {
if (*matched_arg == "--") {
return env_files;
}
Expand All @@ -51,7 +67,7 @@ std::vector<Dotenv::env_file_data> Dotenv::GetDataFromArgs(
// `--env-file path`
auto file_path = std::next(matched_arg);

if (file_path == args.end()) {
if (file_path == options_end) {
return env_files;
}

Expand All @@ -60,7 +76,7 @@ std::vector<Dotenv::env_file_data> Dotenv::GetDataFromArgs(
env_files.push_back(env_file_data);
}

matched_arg = std::find_if(++matched_arg, args.end(), find_match);
matched_arg = std::find_if(++matched_arg, options_end, find_match);
}

return env_files;
Expand Down
21 changes: 21 additions & 0 deletions src/node_options.cc
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,27 @@ void Parse(
args, exec_args, v8_args, options, required_env_settings, errors);
}

size_t GetNodeOptionsEnd(const StringVector& args) {
// The bare config file flags take no value. Spell them out the way the
// config file reader does before the real parse, otherwise the parser would
// consume the next argument as the path.
StringVector remaining;
remaining.reserve(args.size());
for (const std::string& arg : args) {
remaining.push_back(IsBareConfigFileFlag(arg) ? DefaultConfigFileArg()
: arg);
}

// Any errors are reported by the real parse later on.
PerProcessOptions options;
StringVector v8_args;
StringVector errors;
Parse(&remaining, nullptr, &v8_args, &options, kDisallowedInEnvvar, &errors);

// `remaining` is left with the program name and the unparsed arguments.
return args.size() - remaining.size() + 1;
}

// XXX: If you add an option here, please also add it to doc/node.1 and
// doc/api/cli.md
// TODO(addaleax): Make that unnecessary.
Expand Down
28 changes: 28 additions & 0 deletions src/node_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
#include "node_constants.h"
Expand Down Expand Up @@ -795,8 +796,35 @@ void Parse(StringVector* const args,
OptionEnvvarSettings required_env_settings,
StringVector* const errors);

// Returns the index of the first entry in `args` that is neither the program
// name nor an option for Node.js itself. Everything from there on is the
// script and its arguments, or follows `--`, so it must not be read as an
// option of Node.js. This is determined with a throwaway parse, which stops
// exactly where the real parse will.
size_t GetNodeOptionsEnd(const StringVector& args);

} // namespace options_parser

constexpr std::string_view kConfigFileFlag = "--config-file";
// TODO(marco-ippolito): Remove these aliases in a semver-major.
constexpr std::string_view kExperimentalConfigFileFlag =
"--experimental-config-file";
constexpr std::string_view kDefaultConfigFileFlag =
"--experimental-default-config-file";
constexpr std::string_view kDefaultConfigFileName = "node.config.json";

// The config file flags that take no value. Before the real parse they are
// spelled out as `--config-file=node.config.json`.
inline bool IsBareConfigFileFlag(std::string_view arg) {
return arg == kConfigFileFlag || arg == kExperimentalConfigFileFlag ||
arg == kDefaultConfigFileFlag;
}

inline std::string DefaultConfigFileArg() {
return std::string(kConfigFileFlag) + "=" +
std::string(kDefaultConfigFileName);
}

// Helper macro for passing bit-field members to AddOption(). Expands to a
// getter and setter function pointer pair that can read/write the named
// bit-field without requiring a pointer-to-member (which is illegal for
Expand Down
85 changes: 85 additions & 0 deletions test/parallel/test-dotenv-args-after-script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
'use strict';

require('../common');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const tmpdir = require('../common/tmpdir');

// Env file flags are options of Node.js only when they appear before the
// script name. After it they belong to the script, which must receive them
// untouched without the file being read.

tmpdir.refresh();

const envFile = path.join(tmpdir.path, 'test.env');
fs.writeFileSync(envFile, 'FOO=fromfile\nNODE_OPTIONS=--stack-trace-limit=7\n');

const script = path.join(tmpdir.path, 'script.js');
fs.writeFileSync(script, `
console.log(JSON.stringify({
foo: process.env.FOO ?? null,
limit: Error.stackTraceLimit,
args: process.argv.slice(2),
}));
`);

const env = { ...process.env };
delete env.NODE_OPTIONS;
delete env.FOO;

function run(args) {
const child = spawnSync(process.execPath, args, { env, encoding: 'utf8' });
assert.strictEqual(child.status, 0, child.stderr);
return JSON.parse(child.stdout);
}

// Before the script the file is still read.
for (const flagArgs of [
[`--env-file=${envFile}`],
['--env-file', envFile],
[`--env-file-if-exists=${envFile}`],
['--env-file-if-exists', envFile],
]) {
assert.deepStrictEqual(run([...flagArgs, script, 'one']),

Check failure on line 45 in test/parallel/test-dotenv-args-after-script.js

View workflow job for this annotation

GitHub Actions / aarch64-darwin: with shared libraries / build

--- stderr --- node:internal/assert/utils:146 throw error; ^ AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + actual - expected { args: [ 'one' ], foo: 'fromfile', + limit: 10 - limit: 7 } at Object.<anonymous> (/Users/runner/work/_temp/node-v28.0.0-nightly2026-11-20ef7350905d-slim/test/parallel/test-dotenv-args-after-script.js:45:10) at Module._compile (node:internal/modules/cjs/loader:1989:14) at Object..js (node:internal/modules/cjs/loader:2129:10) at Module.load (node:internal/modules/cjs/loader:1711:32) at Module._load (node:internal/modules/cjs/loader:1501:12) at wrapModuleLoad (node:internal/modules/cjs/loader:261:19) at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:166:5) at node:internal/main/run_main_module:33:47 { generatedMessage: true, code: 'ERR_ASSERTION', actual: { foo: 'fromfile', limit: 10, args: [ 'one' ] }, expected: { foo: 'fromfile', limit: 7, args: [ 'one' ] }, operator: 'deepStrictEqual', diff: 'simple' } Node.js v28.0.0-pre Command: out/Release/node /Users/runner/work/_temp/node-v28.0.0-nightly2026-11-20ef7350905d-slim/test/parallel/test-dotenv-args-after-script.js

Check failure on line 45 in test/parallel/test-dotenv-args-after-script.js

View workflow job for this annotation

GitHub Actions / x86_64-darwin: with shared libraries / build

--- stderr --- node:internal/assert/utils:146 throw error; ^ AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + actual - expected { args: [ 'one' ], foo: 'fromfile', + limit: 10 - limit: 7 } at Object.<anonymous> (/Users/runner/work/_temp/node-v28.0.0-nightly2026-11-20ef7350905d-slim/test/parallel/test-dotenv-args-after-script.js:45:10) at Module._compile (node:internal/modules/cjs/loader:1989:14) at Object..js (node:internal/modules/cjs/loader:2129:10) at Module.load (node:internal/modules/cjs/loader:1711:32) at Module._load (node:internal/modules/cjs/loader:1501:12) at wrapModuleLoad (node:internal/modules/cjs/loader:261:19) at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:166:5) at node:internal/main/run_main_module:33:47 { generatedMessage: true, code: 'ERR_ASSERTION', actual: { foo: 'fromfile', limit: 10, args: [ 'one' ] }, expected: { foo: 'fromfile', limit: 7, args: [ 'one' ] }, operator: 'deepStrictEqual', diff: 'simple' } Node.js v28.0.0-pre Command: out/Release/node /Users/runner/work/_temp/node-v28.0.0-nightly2026-11-20ef7350905d-slim/test/parallel/test-dotenv-args-after-script.js
{ foo: 'fromfile', limit: 7, args: ['one'] });
}

// After the script the file is not read and the arguments are kept.
for (const flagArgs of [
[`--env-file=${envFile}`],
['--env-file', envFile],
[`--env-file-if-exists=${envFile}`],
['--env-file-if-exists', envFile],
['--env-file=missing.env'],
]) {
assert.deepStrictEqual(run([script, ...flagArgs]),
{ foo: null, limit: 10, args: flagArgs });
assert.deepStrictEqual(run([script, 'one', ...flagArgs]),
{ foo: null, limit: 10, args: ['one', ...flagArgs] });
}

// A file before the script is read while the same flag after it is ignored.
assert.deepStrictEqual(
run([`--env-file=${envFile}`, script, '--env-file=missing.env']),
{ foo: 'fromfile', limit: 7, args: ['--env-file=missing.env'] });

// Nothing is read after the separator either.
assert.deepStrictEqual(
run(['--', script, `--env-file=${envFile}`]),
{ foo: null, limit: 10, args: [`--env-file=${envFile}`] });

// A missing file before the script still stops the startup.
{
const child = spawnSync(process.execPath,
['--env-file=missing.env', script],
{ env, encoding: 'utf8' });
assert.strictEqual(child.status, 9);
assert.match(child.stderr, /missing\.env: not found/);
}

// Options of Node.js between the file and the script do not hide it.
assert.deepStrictEqual(
run([`--env-file=${envFile}`, '--no-warnings', '-r', 'node:path', script]),
{ foo: 'fromfile', limit: 7, args: [] });
Loading