Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

src: don't overwrite environment from .env file #49424

21 changes: 13 additions & 8 deletions src/node_dotenv.cc
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,19 @@ void Dotenv::SetEnvironment(node::Environment* env) {
for (const auto& entry : store_) {
auto key = entry.first;
auto value = entry.second;
env->env_vars()->Set(
isolate,
v8::String::NewFromUtf8(
isolate, key.data(), NewStringType::kNormal, key.size())
.ToLocalChecked(),
v8::String::NewFromUtf8(
isolate, value.data(), NewStringType::kNormal, value.size())
.ToLocalChecked());

auto existing = env->env_vars()->Get(key.data());

if (existing.IsNothing()) {
philnash marked this conversation as resolved.
Show resolved Hide resolved
env->env_vars()->Set(
isolate,
v8::String::NewFromUtf8(
isolate, key.data(), NewStringType::kNormal, key.size())
.ToLocalChecked(),
v8::String::NewFromUtf8(
isolate, value.data(), NewStringType::kNormal, value.size())
.ToLocalChecked());
}
}
}

Expand Down
12 changes: 12 additions & 0 deletions test/parallel/test-dotenv-edge-cases.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,16 @@ describe('.env supports edge cases', () => {
assert.strictEqual(child.code, 0);
});

it('should not override existing environment variables', async () => {
const code = `
require('assert').strictEqual(process.env.BASIC, 'existing');
`.trim();
const child = await common.spawnPromisified(
process.execPath,
[ `--env-file=${validEnvFilePath}`, '--eval', code ],
{ cwd: __dirname, env: { BASIC: 'existing' } },
);
assert.strictEqual(child.stderr, '');
assert.strictEqual(child.code, 0);
});
GeoffreyBooth marked this conversation as resolved.
Show resolved Hide resolved
});
Loading