NodeJS为exec设置环境变量

时间:2023-01-26 23:21:07

I want to set an environment variable when running a program via child_process.exec. Is this possible?

我想通过child_process.exec运行程序时设置一个环境变量。这可能吗?

I tried setting the env like this:

我尝试像这样设置env:

exec('FOO', {'FOO': 'ah'}, function(error, stdout, stderr) {console.log(stdout, stderr, error);});

but the resulting message said FOO did not exist.

但由此产生的消息说FOO不存在。

1 个解决方案

#1


42  

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

#1


42  

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