Setting Environment Variables for Node to retrieve

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

    I highly recommend looking into the dotenv package.

    https://github.com/motdotla/dotenv

    It's kind of similar to the library suggested within the answer from @Benxamin, but it's a lot cleaner and doesn't require any bash scripts. Also worth noting that the code base is popular and well maintained.

    Basically you need a .env file (which I highly recommend be ignored from your git/mercurial/etc):

    FOO=bar
    BAZ=bob
    

    Then in your application entry file put the following line in as early as possible:

    require('dotenv').config();
    

    Boom. Done. 'process.env' will now contain the variables above:

    console.log(process.env.FOO);
    // bar
    

    The '.env' file isn't required so you don't need to worry about your app falling over in it's absence.

提交回复
热议问题