简体   繁体   中英

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:

// 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.

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. Child processes cannot change the environment of their parent processes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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