【问题标题】:Different env variables for testing and development in nodejsnodejs中用于测试和开发的不同环境变量
【发布时间】:2018-07-04 04:38:59
【问题描述】:

我在空闲时间开发一个nodejs api,我现在正在尝试实现测试。我目前正在从 .env 文件中加载我的环境变量(使用 dotenv 加载),其中包括用于我的开发 mongodb 数据库的 DB_URIDB_USERDB_PASSWORD

现在,我想创建一个单独的数据库进行测试,但是我不知道如何加载不同的变量来连接到测试数据库而不是开发数据库。我部署到 Heroku,在那里我有不同的环境变量,所以这很好。

我尝试在网上寻找一些最佳做法的答案,但一直找不到。我想创建一个不同的 .env 文件,但是根据the documentation on npmjs. 不建议这样做。

推荐的其他资源建议在 package.json 脚本中对我需要的特定变量进行硬编码。但是,如果我必须更改连接到不同数据库所需的所有变量,该脚本将非常庞大。

我可以得到一些帮助来了解我应该如何做到这一点吗?

谢谢!

PS:如果需要,我将使用 mochasupertest 进行测试。

【问题讨论】:

    标签: node.js mongodb environment-variables mocha.js


    【解决方案1】:

    您可以按如下方式使用dotenv 包:

    1. 在您的 .env 文件中,为每个环境添加变量:

      DB_URI_DEVELOPMENT="https://someuri.com"
      DB_USER_DEVELOPMENT=someuser
      DB_PASSWORD_DEVELOPMENT=somepassword
      
      DB_URI_TEST="https://otheruri.com"
      DB_USER_TEST=otheruser
      DB_PASSWORD_TEST=otherpassword
      
    2. development启动应用:

       NODE_ENV=development node server.js
      

      test:

       NODE_ENV=test node server.js
      
    3. 访问应用中的环境变量:

      /**
       * This `if` block prevents loading of the .env file on Heroku by calling
       * dotenv.config() if and only if `NODE_ENV` is not equal to "production"
       *  
       * In order to set environment variables on Heroku, use "config vars":
       * @see {@link https://devcenter.heroku.com/articles/config-vars}.
       *
       * If you must use `dotenv` to load an .env file on Heroku, follow:
       * @see {@link https://stackoverflow.com/a/54884602/1526037}.
       */
      if (process.env.NODE_ENV !== 'production') {
        require('dotenv').config();
      }
      
      // Get the current environment, and convert to uppercase (e.g. "PRODUCTION").
      const env = process.env.NODE_ENV.toUpperCase();
      
      // Access the environment variables for the current environment
      // by postfixing them with the uppercase environment string.
      const {
        [`DB_URI_${env}`]: dbUri,
        [`DB_USER_${env}`]: dbUser,
        [`DB_PASSWORD_${env}`]: dbPassword,
      } = process.env;
      
      /*
       * Note, the above is the same as:
       * ---------------------------------------------------------
       * var dbUri = process.env['DB_URI_' + env];
       * var dbUser = process.env['DB_USER_' + env];
       * var dbPassword = process.env['DB_PASSWORD_' + env];
       */
      

    【讨论】:

    • 嗨@sbolel 这个解决方案heroku兼容吗?
    • 是的,它是@Enrique。对于 Heroku,您有两个用于定义环境变量的选项。 1)您只能在本地使用dotenv,而对于生产,在 Heroku 界面中定义 "config vars" 并在您的应用程序中将它们作为环境变量(process.env)访问,或者(2)您可以在生产中使用 dotenv也可以关注the directions in this answer
    • 非常感谢@sbolel
    • @Enrique 不客气!希望能解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2020-01-23
    • 2021-03-11
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多