简体   繁体   English

在调用的nodejs脚本中设置“流程环境”

[英]Setting the 'process environment' within the called nodejs script

我如何在脚本本身内更改环境,以便其他后续代码将忽略调用环境的状态,并认为该环境是我设置的。

I'm not sure what you mean by 'succeeding code'. 我不确定“成功代码”是什么意思。

If you mean 'within the same Node process' , it's easy: 如果您的意思是“在同一Node进程内” ,这很简单:

// process.env.PATH = 'foobar';
require('child_process').exec('ls', function(err, result) {
  if (err)
    console.log('error', err);
  else
    console.log('ls', result);
});

Try this script with the first line commented out at first, and it'll work just fine. 尝试使用此脚本,并首先注释掉第一行,它将正常工作。 After that, remove the comments so PATH is overwritten by nonsense, and the exec will fail because it can't find the ls command in your PATH anymore. 之后,删除注释,以便PATH被废话覆盖,并且该exec将失败,因为它再也无法在PATH中找到ls命令。

If you mean 'for any following Node processes I might start after my first script' , it's not possible, since the parent process of those following processes is your shell and not your script. 如果您的意思是“对于任何后续的Node进程,我可能会在第一个脚本之后启动” ,这是不可能的,因为这些后续进程的父进程是您的Shell,而不是您的脚本。 Child processes cannot change the environment of their parent processes. 子进程不能更改其父进程的环境。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM