diff --git a/src/node.cc b/src/node.cc index e6be00eeb3c185f..1f0b41061fe0785 100644 --- a/src/node.cc +++ b/src/node.cc @@ -124,6 +124,7 @@ #include #include #include +#include #include #include @@ -844,10 +845,16 @@ static ExitCode InitializeNodeWithArgsInternal( auto file_path = node::Dotenv::GetPathFromArgs(*argv); if (file_path.has_value()) { - auto cwd = Environment::GetCwd(Environment::GetExecPath(*argv)); - std::string path = cwd + kPathSeparator + file_path.value(); CHECK(!per_process::v8_initialized); - per_process::dotenv_file.ParsePath(path); + auto filesystem_path = std::filesystem::path(*file_path); + + if (filesystem_path.is_absolute()) { + per_process::dotenv_file.ParsePath(*file_path); + } else { + auto cwd = Environment::GetCwd(Environment::GetExecPath(*argv)); + std::string path = cwd + kPathSeparator + file_path.value(); + per_process::dotenv_file.ParsePath(path); + } per_process::dotenv_file.AssignNodeOptionsIfAvailable(&node_options); } diff --git a/test/parallel/test-dotenv-edge-cases.js b/test/parallel/test-dotenv-edge-cases.js index 1d256799bfbb136..a1cf7d4dc7a8a50 100644 --- a/test/parallel/test-dotenv-edge-cases.js +++ b/test/parallel/test-dotenv-edge-cases.js @@ -2,10 +2,12 @@ const common = require('../common'); const assert = require('node:assert'); +const path = require('node:path'); const { describe, it } = require('node:test'); const validEnvFilePath = '../fixtures/dotenv/valid.env'; const relativePath = '../fixtures/dotenv/node-options.env'; +const absolutePath = path.join(__dirname, relativePath); describe('.env supports edge cases', () => { @@ -35,4 +37,17 @@ describe('.env supports edge cases', () => { assert.strictEqual(child.code, 0); }); + it('should support absolute paths', async () => { + const code = ` + require('assert').strictEqual(process.env.CUSTOM_VARIABLE, 'hello-world'); + `.trim(); + const child = await common.spawnPromisified( + process.execPath, + [ `--env-file=${absolutePath}`, '--eval', code ], + { cwd: __dirname }, + ); + assert.strictEqual(child.stderr, ''); + assert.strictEqual(child.code, 0); + }); + });