55

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.

2 Answers 2

89

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Anyone using this should take note that specifying environment variables this way replaces the entire set of environment variables, including any PATH that might otherwise exist. So, if you try to set an env variable and you suddenly get errors about the command you're trying to exec not being found, this is why. This isn't clear at all from the documentation and left me scratching my head for a bit. If you want to add env variables and stay platform-agnostic, you could make a copy of process.env, apply your changes to that, and pass it to child_process.exec.
You can also update process.env direclty. Ex: process.env["PATH"] += path.delimiter + process.cwd() + path.sep + "node_modules" + path.sep + ".bin"
complementing @DanielSmedegaardBuus answer, you can use the spread operator for it. env: { ...process.env, 'FOO': 'ah'}
47

Based on @DanielSmedegaardBuus answer, you have to add your env var to the existing ones, if you want to preserve them:

const { exec } = require("child_process");

exec(
  "echo $FOO", 
  { env: { ...process.env, FOO: "ah" } }, 
  function (error, stdout, stderr) {
    console.log(stdout, stderr, error);
  }
);

1 Comment

Yes, that's what I should've written :D My name is DanielSmedegaardBuus, and I endorse this message :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.