Setting Environment Variables for Node to retrieve

前端 未结 16 2095
-上瘾入骨i
-上瘾入骨i 2020-11-22 15:41

I\'m trying to follow a tutorial and it says:

There are a few ways to load credentials.

  1. Loaded from environment variables,
16条回答
  •  悲&欢浪女
    2020-11-22 16:36

    A very good way of doing environment variables I have successfully used is below:

    A. Have different config files:

    1. dev.js // this has all environment variables for development only
      The file contains:

      module.exports = {
       ENV: 'dev',
       someEnvKey1 : 'some DEV Value1',
       someEnvKey2 : 'some DEV Value2'
      };
      
    2. stage.js // this has all environment variables for development only

      ..
      
    3. qa.js // this has all environment variables for qa testing only
      The file contains:

      module.exports = {
       ENV: 'dev',
       someEnvKey1 : 'some QA Value1',
       someEnvKey2 : 'some QA Value2'
      };
      

    NOTE: the values are changing with the environment, mostly, but keys remain same.

    1. you can have more

    2. z__prod.js // this has all environment variables for production/live only
      NOTE: This file is never bundled for deployment

    3. Put all these config files in /config/ folder

      /config/dev.js
      /config/qa.js
      /config/z__prod.js
      /setenv.js
      /setenv.bat
      /setenv.sh
      

    NOTE: The name of prod is different than others, as it would not be used by all.

    B. Set the OS/ Lambda/ AzureFunction/ GoogleCloudFunction environment variables from config file

    Now ideally, these config variables in file, should go as OS environment variables (or, LAMBDA function variables, or, Azure function variables, Google Cloud Functions, etc.)

    so, we write automation in Windows OS (or other)

    1. Assume we write 'setenv' bat file, which takes one argument that is environment that we want to set

    2. Now run "setenv dev"

    a) This takes the input from the passed argument variable ('dev' for now)
    b) read the corresponding file ('config\dev.js')
    c) sets the environment variables in Windows OS (or other)

    For example,

    The setenv.bat contents might be:

        node setenv.js
    

    The setenv.js contents might be:

        // import "process.env.ENV".js file (dev.js example)
        // loop the imported file contents
        //     set the environment variables in Windows OS (or, Lambda, etc.)
    

    That's all, your environment is ready for use.

    When you do 'setenv qa', all qa environment variables will be ready for use from qa.js, and ready for use by same program (which always asks for process.env.someEnvKey1, but the value it gets is qa one).

    Hope that helps.

提交回复
热议问题