Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS set environment variable for exec

Tags:

node.js

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.

like image 286
Tower Avatar asked Oct 19 '11 16:10

Tower


People also ask

Do we need to set environment variables for node JS?

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.

How do I set environment variables?

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.


2 Answers

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);
});
like image 143
Chris F Avatar answered Oct 25 '22 20:10

Chris F


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);
  }
);
like image 44
rap-2-h Avatar answered Oct 25 '22 20:10

rap-2-h