Setting Environment Variables for Node to retrieve

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

    Windows-users: pay attention! These commands are recommended for Unix but on Windows they are only temporary. They set a variable for the current shell only, as soon as you restart your machine or start a new terminal shell, they will be gone.

    • SET TEST="hello world"
    • $env:TEST = "hello world"

    To set a persistent environment variable on Windows you must instead use one of the following approaches:

    A) .env file in your project - this is the best method because it will mean your can move your project to other systems without having to set up your environment vars on that system beore you can run your code.

    1. Create an .env file in your project folder root with the content: TEST="hello world"

    2. Write some node code that will read that file. I suggest installing dotenv ( npm install dotenv --save) and then add require('dotenv').config(); during your node setup code.

    3. Now your node code will be able to accessprocess.env.TEST

    Env-files are a good of keeping api-keys and other secrets that you do not want to have in your code-base. Just make sure to add it to your .gitignore .

    B) Use Powershell - this will create a variable that will be accessible in other terminals. But beware, the variable will be lost after you restart your computer.

    [Environment]::SetEnvironmentVariable("TEST", "hello world", "User")

    This method is widely recommended on Windows forums, but I don't think people are aware that the variable doesn't persist after a system restart....

    C) Use the Windows GUI

    1. Search for "Environment Variables" in the Start Menu Search or in the Control Panel
    2. Select "Edit the system environment variables"
    3. A dialogue will open. Click the button "Environment Variables" at the bottom of the dialogue.
    4. Now you've got a little window for editing variables. Just click the "New" button to add a new environment variable. Easy.

提交回复
热议问题