Home > OS >  how do i tell my node/ express app if it should use test.env or dev.env on mac?
how do i tell my node/ express app if it should use test.env or dev.env on mac?

Time:01-02

how do i tell my node/ express app if it should use test.env or dev.env on mac?

I essentially want to be able to run my app and tell it which database to connect to; (dev or test). However the app always selects 'test.env'.

I am calling

process.env.DBNAME

in order to select the environment variable that stores my database name.

Would also be nice to know how to select the environment when I deploy my app in production.

I don't know what else to try and would really appreciate help!

CodePudding user response:

You can use the dotenv package as follows:

  1. Add a .env file and In your .env file, add variables for each environment:

    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. Start the application in development:

NODE_ENV=development node server.js

or in test:

NODE_ENV=test node server.js

Access the environment variables in your app:

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}


const env = process.env.NODE_ENV.toUpperCase();

Access the environment variables for the current environment by postfixing them with the uppercase environment string.

 var dbUri = process.env['DB_URI_'   env];
 var dbUser = process.env['DB_USER_'   env];
 var dbPassword = process.env['DB_PASSWORD_'   env];

CodePudding user response:

You can use this package to pass different env files. https://www.npmjs.com/package/env-cmd

  • Related