我在空闲时间开发一个nodejs api,我现在正在尝试实现测试。我目前正在从 .env 文件(使用 dotenv
加载)加载我的环境变量,其中包括 DB_URI
、DB_USER
和 DB_PASSWORD
用于我的开发 mongodb 数据库。
现在,我想创建一个单独的数据库进行测试,但是我不知道如何加载不同的变量来连接到测试数据库而不是开发数据库。我部署到 Heroku,在那里我有不同的环境变量,所以这很好。
我试图在网上寻找一些最佳做法的答案,但一直找不到。我想创建一个不同的 .env 文件,但是根据 the documentation on npmjs. 不建议这样做.
推荐的其他资源建议在 package.json 脚本中对我需要的特定变量进行硬编码。但是,如果我必须更改连接到不同数据库所需的所有变量,该脚本将非常庞大。
我能否获得一些帮助以了解我应该如何做到这一点?
谢谢!
PS:如果需要,我使用 mocha
和 supertest
进行测试。
最佳答案
您可以使用 dotenv
打包如下:
在您的
.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
在
开发
中启动应用程序:NODE_ENV=development node server.js
或在
测试
:NODE_ENV=test node server.js
访问应用中的环境变量:
/** * 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]; */
关于node.js - nodejs中用于测试和开发的不同环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48434261/