在Node中使用环境变量 [英] Using environment variables in Node

查看:128
本文介绍了在Node中使用环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试为本地和生产Web应用程序提供一种具有不同环境变量的简化方法,但是我还没有遇到过理想"的解决方案.

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.

可以选择具有这样的config.js文件:

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

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

并通过ES6导入进行访问

And accessing via ES6 imports

或使用.env文件,如下所示:

Or using .env files like so:

SOME_KEY=someValue
HELLO=world
FACEBOOK_SECRET=435SDFSF5DZVD7S

然后使用dotenv在代码中通过process.env访问变量.

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.

那么您如何在生产环境中使用单独的文件? dotenv文档说,他们强烈建议不要使用.local.env和.prod.env.

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.

此外,如何最好地推送到远程服务器?我有自己的带有Gulp任务的服务器,该任务在Git接收后挂钩上运行.如何最好地将生产环境变量传递到此处?

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?

谢谢

推荐答案

对于每种环境,您都可以拥有自己的配置文件:

You could have own config file for each environment:

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

要使用适当的配置文件,请使用必需的NODE_ENV运行应用程序:

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

NODE_ENV=production node index

environments/index.js中确定当前的NODE_ENV并使用config:

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);

如果配置文件不包含秘密信息(apiKeys等),则可以将其推送到存储库中.否则,将其添加到.gitignore并在服务器上使用环境变量.

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.

注意:

对于高级配置,请使用诸如 nconf 之类的软件包.

For advanced configuration use such packages as nconf.

它允许使用文件,环境变量,命令行参数和原子对象合并来创建分层的node.js配置.

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

这篇关于在Node中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆