Adding .env vairables to run in for a given comman

2019-05-11 18:54发布

问题:

I have a .env file with variables in it like this:

HELLO=world
SOMETHING=nothing

I found this awesome script the other day, that puts these variables into the current session so when I run something like this

$(cat ./.env | grep -v ^# | xargs) && node test

Then I can access the variables in the test.js node file.

console.log(process.env.HELLO)
console.log(process.env.SOMETHING)

The problem with this is that that command puts the .env variables in the entire session so when I run node test without $(cat ./.env | grep -v ^# | xargs) after I run it, it will still have access to those variables, I'm writing a node.js test that accounts for these variables and I'd love to be able to run the same command with and without these .env variables without worrying if they are still in the session. Ideally I want to run

put-env-variables-for-this-command-first-command node test && node test

And have the env variables only be available in the test script the first time it runs.

回答1:

This will give you access to the variables during the invocation of node test only

env $(<.env) node test


回答2:

I started using foreman for this which used to be bundled with the heroku toolbelt. It's not included anymore, however there is a stand-alone version called forego that works really well.

brew install forego on the mac.

Then you can use this to prop-up the .env variables into the current process.

forego run ${ANY COMMAND}

Examples

  • forego run babel-node index.js
  • forego run node index.js
  • forego run npm start