简体   繁体   English

如果我使用 dotenv 和 PM2生态系统.config.js 设置环境变量,Node 将使用哪一个?

[英]If I set env vars using dotenv and PM2 ecosystem.config.js, which one will Node use?

I assume PM2 appends env vars the 'native' system way at startup, something like:我假设 PM2 在启动时以“本机”系统方式附加 env vars,例如:

 MYVAR=hey; node app.js

The difference with the dotenv npm package is it MUST append vars another way, because it works inside the script (it can't do MYVAR=someothervar; node app.js because the program is already started), so it works like this:dotenv npm 包的区别在于它必须以另一种方式附加 vars,因为它在脚本内部工作(它不能执行MYVAR=someothervar; node app.js因为程序已经启动),所以它的工作方式如下:

dotenv.config() //reads .env file and appends stuff to process.env at runtime

Now say PM2 launches MYVAR=hey; node app.js现在说 PM2 启动MYVAR=hey; node app.js MYVAR=hey; node app.js and then inside app.js we run dotenv.config() that reads an .env file containing MYVAR=foo . MYVAR=hey; node app.js然后在 app.js 中运行dotenv.config()读取包含MYVAR=foo的 .env 文件。 Which var will be in process.env?哪个 var 将在 process.env 中?

ecosystem.config.js生态系统配置文件

{
  //...standard pm2 config above
  env: {
     MYVAR: 'ecosystem',
   },
}

.env/dotenv .env/dotenv

MYVAR=dotenv

Code代码

dotenv.config()
console.log(process.env.MYVAR)

dotenv.config() will not overwrite variables if it sees they already exist in the process.env (that they've been assigned the PM2 MYVAR=foo; node app.js way. dotenv.config()发现它们已存在于process.env (它们已被分配 PM2 MYVAR=foo; node app.js方式dotenv.config()则不会覆盖它们。

So process envs set before launch will take precedence.因此,在启动之前设置的进程环境将优先。

This is actually in the README of dotenv.这实际上在 dotenv 的 README 中。

What happens to environment variables that were already set?已经设置的环境变量会发生什么?

We will never modify any environment variables that have already been set.我们永远不会修改任何已经设置的环境变量。 In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped.特别是,如果 .env 文件中有一个变量与环境中已经存在的变量发生冲突,那么该变量将被跳过。 This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.此行为允许您使用特定于机器的环境覆盖所有 .env 配置,但不建议这样做。

https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set

If you absolutely need to override existing env vars - use the dotenv-override package.如果您绝对需要覆盖现有的环境变量 - 使用dotenv-override包。

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

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