Setting Environment Variables for Node to retrieve

前端 未结 16 2096
-上瘾入骨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:14

    If you want a management option, try the envs npm package. It returns environment values if they are set. Otherwise, you can specify a default value that is stored in a global defaults object variable if it is not in your environment.

    Using .env ("dot ee-en-vee") or environment files is good for many reasons. Individuals may manage their own configs. You can deploy different environments (dev, stage, prod) to cloud services with their own environment settings. And you can set sensible defaults.

    Inside your .env file each line is an entry, like this example:

    NODE_ENV=development
    API_URL=http://api.domain.com
    TRANSLATION_API_URL=/translations/
    GA_UA=987654321-0
    NEW_RELIC_KEY=hi-mom
    SOME_TOKEN=asdfasdfasdf
    SOME_OTHER_TOKEN=zxcvzxcvzxcv
    

    You should not include the .env in your version control repository (add it to your .gitignore file).

    To get variables from the .env file into your environment, you can use a bash script to do the equivalent of export NODE_ENV=development right before you start your application.

    #!/bin/bash
    while read line; do export "$line";
    done 

    Then this goes in your application javascript:

    var envs = require('envs');
    
    // If NODE_ENV is not set, 
    // then this application will assume it's prod by default.
    app.set('environment', envs('NODE_ENV', 'production')); 
    
    // Usage examples:
    app.set('ga_account', envs('GA_UA'));
    app.set('nr_browser_key', envs('NEW_RELIC_BROWSER_KEY'));
    app.set('other', envs('SOME_OTHER_TOKEN));
    

提交回复
热议问题