I want to set an environment variable when running a program via child_process.exec
. Is this possible?
I tried setting the env
like this:
exec('FOO', {'FOO': 'ah'}, function(error, stdout, stderr) {console.log(stdout, stderr, error);});
but the resulting message said FOO did not exist.
You really do not need to set up your own environment to start learning Node. js. Reason is very simple, we already have set up Node.
On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.
You have to pass an options object that includes the key env whose value is itself an object of key value pairs.
exec('echo $FOO', {env: {'FOO': 'ah'}}, function (error, stdout, stderr)
{
console.log(stdout, stderr, error);
});
Based on @DanielSmedegaardBuus answer, you have to add your env var to the existing ones, if you want to preserve them:
exec(
"echo $FOO",
{ env: { ...process.env, FOO: "ah" } },
function (error, stdout, stderr) {
console.log(stdout, stderr, error);
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With