node.js 为节点设置环境变量以检索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22312671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:59:42  来源:igfitidea点击:

Setting Environment Variables for Node to retrieve

node.jsenvironment-variables

提问by user1107173

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

我正在尝试按照教程进行操作,它说:

There are a few ways to load credentials.

  1. Loaded from environment variables,
  2. Loaded from a JSON file on disk,

The keys need to be as follows:

USER_ID, USER_KEY

...This means that if you properly set your environment variables, you do not need to manage credentials in your application at all.

有几种方法可以加载凭据。

  1. 从环境变量加载,
  2. 从磁盘上的 JSON 文件加载,

密钥需要如下:

USER_ID, USER_KEY

...这意味着,如果您正确设置了环境变量,则根本不需要管理应用程序中的凭据。

Based on some Googling, it appears that I need to set the variables in process.env? How and where do I set these credentials? Example Please.

基于一些谷歌搜索,看来我需要在process.env? 如何以及在哪里设置这些凭据?请举例。

采纳答案by SamT

Environment variables (in this case) are being used to pass credentials to your application. USER_IDand USER_KEYcan both be accessed from process.env.USER_IDand process.env.USER_KEYrespectively. You don't need to edit them, just access their contents.

环境变量(在本例中)用于将凭据传递给您的应用程序。USER_IDUSER_KEY都可以分别从process.env.USER_ID和访问process.env.USER_KEY。您不需要编辑它们,只需访问它们的内容即可。

It looks like they are simply giving you the choice between loading your USER_IDand USER_KEYfrom either process.envor some specificed file on disk.

看起来他们只是让您选择从磁盘上的任一文件或某些特定文件加载USER_ID和。USER_KEYprocess.env

Now, the magic happens when you run the application.

现在,当您运行应用程序时,神奇就发生了。

USER_ID=239482 USER_KEY=foobar node app.js

USER_ID=239482 USER_KEY=foobar node app.js

That will pass the user id 239482and the user key as foobar. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.

这会将用户 ID239482和用户密钥作为foobar. 这适用于测试,但是对于生产,您可能会配置一些 bash 脚本来导出变量。

回答by ctrlplusb

I highly recommend looking into the dotenv package.

我强烈建议查看 dotenv 包。

https://github.com/motdotla/dotenv

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.

它有点类似于@Benxamin 的答案中建议的库,但它更简洁,不需要任何 bash 脚本。还值得注意的是,代码库很受欢迎且维护良好。

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

基本上你需要一个 .env 文件(我强烈建议在你的 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:

繁荣。完毕。“process.env”现在将包含上面的变量:

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.

'.env' 文件不是必需的,因此您无需担心您的应用程序在它不存在的情况下会崩溃。

回答by palanik

Just provide the env values on command line

只需在命令行上提供 env 值

USER_ID='abc' USER_KEY='def' node app.js

回答by jsbisht

You can set the environment variable through process global variable as follows:

您可以通过流程全局变量设置环境变量,如下所示:

process.env['NODE_ENV'] = 'production';

Works in all platforms.

适用于所有平台。

回答by Benxamin

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

如果你想要一个管理选项,试试envsnpm 包。如果设置了环境值,它将返回环境值。否则,您可以指定存储在全局默认对象变量中的默认值(如果它不在您的环境中)。

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.

使用.env(“dot ee-en-vee”)或环境文件有很多好处。个人可以管理自己的配置。您可以使用自己的环境设置将不同的环境(dev、stage、prod)部署到云服务。您可以设置合理的默认值。

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

在您的.env文件中,每一行都是一个条目,如下例所示:

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 notinclude the .envin your version control repository (add it to your .gitignorefile).

您不应包含.env在您的版本控制存储库中(将其添加到您的.gitignore文件中)。

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

要将.env文件中的变量放入您的环境中,您可以export NODE_ENV=development在启动应用程序之前使用 bash 脚本执行等效的操作。

#!/bin/bash
while read line; do export "$line";
done <source .env

Then this goes in your application javascript:

然后这会出现在您的应用程序 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));

回答by leszek.hanusz

It depends on your operating system and your shell

这取决于您的操作系统和外壳

On linux with the shell bash, you create environment variables like this(in the console):

带有 shell bash 的 linux 上,您可以创建这样的环境变量(在控制台中):

export FOO=bar

For more information on environment variables on ubuntu (for example):

有关 ubuntu 环境变量的更多信息(例如):

Environment variables on ubuntu

ubuntu 环境变量

回答by dpolicastro

Like ctrlplusb said, I recommend you to use the package dotenv, but another way to do this is creating a js file and requiring it on the first line of your app server.

就像 ctrlplusb 所说的那样,我建议您使用 package dotenv,但另一种方法是创建一个 js 文件并在应用服务器的第一行要求它。

env.js:

环境.js:

process.env.VAR1="Some value"
process.env.VAR2="Another Value"

app.js:

应用程序.js:

require('env')
console.log(process.env.VAR1) // Some value

回答by Drkawashima

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.

Windows 用户:注意!建议在 Unix 上使用这些命令,但在 Windows 上它们只是临时的。它们仅为当前 shell 设置一个变量,只要您重新启动机器或启动新的终端 shell,它们就会消失。

  • SET TEST="hello world"
  • $env:TEST = "hello world"
  • 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:

要在 Windows 上设置持久环境变量,您必须改用以下方法之一:

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.

A) 项目中的 .env 文件- 这是最好的方法,因为这意味着您可以将项目移动到其他系统,而无需在该系统上设置环境变量,然后才能运行代码。

  1. Create an .envfile 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
  1. .env在您的项目文件夹根目录中创建一个包含以下内容的文件:TEST="hello world"

  2. 编写一些将读取该文件的节点代码。我建议安装 dotenv ( npm install dotenv --save) 然后require('dotenv').config();在你的节点设置代码中添加。

  3. 现在您的节点代码将能够访问process.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.

环境文件可以很好地保存您不想在代码库中包含的 api 密钥和其他秘密。只需确保将其添加到您的.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.

B) 使用 Powershell- 这将创建一个可以在其他终端中访问的变量。但请注意,重新启动计算机后该变量将丢失。

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

[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....

这种方法在 Windows 论坛上被广泛推荐,但我认为人们没有意识到系统重启后变量不会持续存在......

C) Use the Windows GUI

C) 使用 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.
  1. 在开始菜单搜索或控制面板中搜索“环境变量”
  2. 选择“编辑系统环境变量”
  3. 将打开一个对话。单击对话框底部的“环境变量”按钮。
  4. 现在您有一个用于编辑变量的小窗口。只需单击“新建”按钮即可添加新的环境变量。简单。

回答by Blairg23

Step 1:Add your environment variables to their appropriate file. For example, your staging environment could be called .env.staging, which contains the environment variables USER_IDand USER_KEY, specific to your staging environment.

步骤 1:将您的环境变量添加到相应的文件中。例如,您的登台环境可以称为.env.staging,其中包含特定于您的登台环境的环境变量USER_IDUSER_KEY

Step 2:In your package.jsonfile, add the following:

第 2 步:在您的package.json文件中,添加以下内容:

"scripts": {
  "build": "sh -ac '. ./.env.${REACT_APP_ENV}; react-scripts build'",
  "build:staging": "REACT_APP_ENV=staging npm run build",
  "build:production": "REACT_APP_ENV=production npm run build",
  ...
}

then call it in your deploy script like this:

然后在您的部署脚本中调用它,如下所示:

npm run build:staging

Super simple set up and works like a charm!

超级简单的设置,就像一个魅力!

Source:https://medium.com/@tacomanator/environments-with-create-react-app-7b645312c09d

来源:https : //medium.com/@tacomanator/environments-with-create-react-app-7b645312c09d

回答by asherrard

For windows users this Stack Overflow question and top answer is quite useful on how to set environement variables via the command line

对于 Windows 用户,此 Stack Overflow 问题和最佳答案对于如何通过命令行设置环境变量非常有用

How can i set NODE_ENV=production in Windows?

如何在 Windows 中设置 NODE_ENV=production?