NodeJS set environment variable for exec

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.


Solution 1:

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);
});

Solution 2:

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);
  }
);