简体   繁体   中英

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:

 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.config() //reads .env file and appends stuff to process.env at runtime

Now say PM2 launches 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 . Which var will be in process.env?

ecosystem.config.js

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

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

So process envs set before launch will take precedence.

This is actually in the README of dotenv.

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. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.

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.

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