Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

node.js - Using environment variables in Node

I have been trying to get a streamline way of having different environment variables for local and production web apps, but I haven't come across the "ideal" solution yet.

There's the option of having a config.js file like so:

//config.js
{
    "secretKey": "SDFDASFFSFD",
    "facebook": {
        "clientID": "EFGFDGBGDGFS",
        "clientSecret": "EGDFNHFG"
    }
}

And accessing via ES6 imports

Or using .env files like so:

SOME_KEY=someValue
HELLO=world
FACEBOOK_SECRET=435SDFSF5DZVD7S

And accessing the variables via process.env in the code using dotenv.

Obviously no matter what route you go down, the file will need to be omitted from version control which is fine. Each of these ways are great, but they only seem to work well for local development.

So how do you then have a separate file for a production environment? The dotenv docs say they strongly recommend against a .local.env and .prod.env situation.

Also, how is best to push to a remote server? I have my own server with Gulp tasks which run on a Git post-receive hook. How is best to pass up the production environment variables to here?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could have own config file for each environment:

- environments
  - index.js
  - deveplopment.json
  - staging.json
  - production.json

To use appropriate config file, run the app with required NODE_ENV:

NODE_ENV=production node index

In environments/index.js determinate the current NODE_ENV and use config:

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
module.exports = require('./' + process.env.NODE_ENV);

If config file doesn't include secret info (apiKeys, etc), it can be pushed to repo. Otherwise add it to .gitignore and use environment variables on the server.

Note:

For advanced configuration use such packages as nconf.

It allows to create hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...