node环境变量_实际使用Node环境变量的方法如下

 2023-09-06 阅读 26 评论 0

摘要:node环境变量Environment variables are a fundamental part of Node development, but for some reason I never bothered with learning how to properly use them. 环境变量是Node开发的基本组成部分,但是由于某些原因,我从不费心去学习如何正确使用它们。 M

node环境变量

Environment variables are a fundamental part of Node development, but for some reason I never bothered with learning how to properly use them.

环境变量是Node开发的基本组成部分,但是由于某些原因,我从不费心去学习如何正确使用它们。

Maybe because they are called “Environment Variables.”

也许是因为它们被称为“环境变量”。

Just the words “Environment Variable” trigger a PTSD-laced flashback in which I am trying to add the correct path to the Java Home directory on Windows. Does it go in PATH or JAVA_HOME or both? Do I need to end it with a semicolon? WHY AM I USING JAVA?

只是单词“ Environment Variable”触发了PTSD标记的闪回,我试图在其中向Windows上的Java Home目录添加正确的路径。 它是放在PATH还是JAVA_HOME中? 我需要以分号结尾吗? 我为什么要使用JAVA?

In Node, environment variables can be global (like on Windows), but are often used with a specific process that you want to run. For instance, if you had a web application, you might have environment variables that define:

在Node中,环境变量可以是全局变量(例如在Windows上),但是通常与要运行的特定进程一起使用。 例如,如果您有一个Web应用程序,则可能具有定义以下内容的环境变量:

  • The HTTP Port to listen on

    侦听的HTTP端口
  • The Database Connection String

    数据库连接字符串
  • The JAVA_HOME…wait…no — sorry. The healing process takes time.

    JAVA_HOME…等等…不,对不起。 康复过程需要时间。

In this context, environment variables are really more like “Configuration Settings.” See how much nicer that sounds?

在这种情况下,环境变量实际上更像是“配置设置”。 看看听起来好多了?

If you’ve done .NET before, you might be familiar with something like a web.config file. Node environment variables work much the same was as settings in a web.config — they’re a way for you to pass in information that you don’t want to hard code.

如果您之前已经完成过.NET,则可能熟悉诸如web.config文件之类的东西。 节点环境变量的工作方式与web.config设置几乎相同,它们是您传递不需要硬编码的信息的一种方式。

But how do you use these variables in your Node application? I had a hard time finding good resources on this with the requisite amount of Java jokes, so I decided to create one. Here are some of the different ways you can define and then read environment variables in your Node applications.

但是,如何在Node应用程序中使用这些变量? 我很难找到必要的Java笑话,以此找到好的资源,因此我决定创建一个。 您可以使用以下几种不同的方法来定义和读取Node应用程序中的环境变量。

通过终端 (Pass it in the terminal)

You can pass environment variables on the terminal as part of your Node process. For instance, if you were running an Express app and wanted to pass in the port, you could do it like this…

您可以在终端上传递环境变量,作为您Node过程的一部分。 例如,如果您正在运行Express应用并想要通过端口,则可以这样操作…

PORT=65534 node bin/www

Fun fact: port 65535 is the largest TCP/IP network value available. How do I know that? StackOverflow of course. How does anybody know anything? But you can only go as high as port 65534 for a web app because that’s the highest port Chrome will connect to. How do I know that? Because Liran Tal told me in the comments. You should follow him. Between the two of us he’s the one who knows what he’s doing.

有趣的事实:端口65535是可用的最大TCP / IP网络值。 我怎么知道 当然是StackOverflow 。 有人怎么知道? 但是对于网络应用程序,您只能使用最高65534的端口,因为这是Chrome可以连接的最高端口。 我怎么知道呢? 因为Liran Tal在评论中告诉我。 你应该跟着他。 在我们两个人之间,他是一个知道自己在做什么的人。

Now to use the variable in your code, you would use the process.env object.

现在要在代码中使用变量,您将使用process.env对象。

var port = process.env.PORT;

But this could get ugly. If you had a connection string, you probably wouldn’t want to start passing multiple variables on the terminal. It would look like you are hoarding configuration values, and someone who loves you could stage an intervention and that would be awkward for everyone involved.

但这可能很难看。 如果您有连接字符串,则可能不想在终端上开始传递多个变量。 看起来您在ho积配置值,一个爱您的人可以进行干预,这对于每个参与其中的人都是尴尬的。

PORT=65534
DB_CONN="mongodb://react-cosmos-db:swQOhAsVjfHx3Q9VXh29T9U8xQNVGQ78lEQaL6yMNq3rOSA1WhUXHTOcmDf38Q8rg14NHtQLcUuMA==@react-cosmos-db.documents.azure.com:10255/?ssl=true&replicaSet=globaldb"
SECRET_KEY="b6264fca-8adf-457f-a94f-5a4b0d1ca2b9"

This doesn’t scale, and everyone wants to scale. According to every architect I’ve ever sat in a meeting with, “scaling” is more important than the application even working.

这无法扩展,每个人都想扩展。 根据我参加过会议的每位建筑师的说法,“缩放”比应用程序甚至工作更为重要。

So let’s look at another way: .env files.

因此,让我们看另一种方式:.env文件。

使用.env文件 (Use a .env file)

.env files allow you to put your environment variables inside a file. You just create a new file called .env in your project and slap your variables in there on different lines.

.env文件允许您将环境变量放入文件中。 您只需在项目中创建一个名为.env的新文件,然后将变量放在不同行中即可。

PORT=65534DB_CONN="mongodb://react-cosmos-db:swQOhAsVjfHx3Q9VXh29T9U8xQNVGQ78lEQaL6yMNq3rOSA1WhUXHTOcmDf38Q8rg14NHtQLcUuMA==@react-cosmos-db.documents.azure.com:10255/?ssl=true&replicaSet=globaldb"SECRET_KEY="b6264fca-8adf-457f-a94f-5a4b0d1ca2b9"

To read these values, there are a couple of options, but the easiest is to use the dotenv package from npm.

要读取这些值,有两个选项,但是最简单的方法是使用npm中的dotenv软件包。

npm install dotenv --save

Then you just require that package in your project wherever you need to use environment variables. The dotenv package will pick up that file and load those settings into Node.

然后,您只需要在项目中需要使用环境变量的任何地方使用该软件包即可。 dotenv软件包将提取该文件并将这些设置加载到Node中。

Use dotenv to read .env vars into Node
require('dotenv').config();
var MongoClient = require('mongodb').MongoClient;// Reference .env vars off of the process.env object
MongoClient.connect(process.env.DB_CONN, function(err, db) {if(!err) {console.log("We are connected");}
});

PROTIP: Don’t check your .env file into Github. It has all you secrets in it and Github will email you and tell you so. Don’t be like me.

提示:不要将您的.env文件签入Github。 它包含了您所有的秘密,Github会通过电子邮件向您发送通知。 别像我

OK — Nice. But this is kind of a pain. You have to put this in every single file where you want to use environment variables AND you have to deploy the dotenv to production where you don’t actually need it. I’m not a huge fan of deploying pointless code, but I guess I just described my whole career.

好的,很好。 但这有点痛苦。 您必须将其放置在要使用环境变量的每个文件中,并且必须将dotenv部署到实际不需要它的生产环境中。 我不是部署无意义代码的忠实拥护者,但是我想我只是描述了我的整个职业生涯。

Luckily, you are using VS Code (because of course you are), so you have some other options.

幸运的是,您正在使用VS Code (因为您当然是 ),因此您还有其他选择。

在VS Code中使用.env文件 (Working with .env files in VS Code)

First off, you can install the DotENV extension for code which will give you nice syntax highlighting in your .env files.

首先,您可以安装DotENV扩展名的代码,这将使您的.env文件中的语法突出显示。

DotENV - Visual Studio MarketplaceExtension for Visual Studio Code - Support for dotenv file syntaxmarketplace.visualstudio.com

DotENV-Visual Studio 代码的 Visual Studio市场 扩展-支持dotenv文件语法 marketplace.visualstudio.com

The VS Code Debugger also offers some more convenient options for loading values from .env files if you are using the VS Code Debugger.

如果您使用的是VS代码调试器VS代码调试程序还提供了装载值的一些更方便的选择从.ENV文件。

VS代码启动配置 (VS Code Launch Configurations)

The Node debugger for VS Code (already there, no need to install anything) supports loading in .env files via launch configurations. You can read more more about Launch Configurations here.

VS Code的Node调试器(已经存在,无需安装任何程序)支持通过启动配置加载.env文件。 您可以在此处有关启动配置的信息 。

When you create a basic Node Launch Configuration (click on the gear and select Node), you can do one or both of two things.

创建基本的“节点启动配置”(单击齿轮并选择“节点”)时,您可以执行以下两项之一或全部。

The first is you can simply pass variables in on the launch config.

首先是您可以在启动配置中简单地传递变量。

This is nice, but the fact that every value has to be a string bothers me a bit. It’s a number, not a string. JavaScript only has, like, 3 types. Don’t take one of them away from me.

很好,但是每个值都必须是字符串的事实令我有些困扰。 这是数字,而不是字符串。 JavaScript仅具有3种类型。 不要把其中一个带走我。

There is a simpler way here. We’ve already learned to love .env files, so instead of passing them, we can just give VS Code the name of the .env file.

这里有一个更简单的方法。 我们已经学会了喜欢.env文件,因此.env传递它们外,我们还可以给VS Code指定.env文件的名称。

And as long as we are starting our process from VS Code, environment variables files are loaded in. We don’t have to mutilate numbers into strings and we aren’t deploying worthless code into production. Well, at least you aren’t.

只要我们从VS Code开始过程,就将加载环境变量文件。我们不必将数字残缺化为字符串,也不会在生产中部署毫无价值的代码。 好吧,至少你不是。

从NPM而不是Node开始 (Starting with NPM instead of Node)

You might have gotten this far and thought, “Burke, I never ever run node anything. It’s always an npm script like npm start”.

您可能已经走了这么远,然后想到:“伯克,我从不运行node 。 它总是像npm start一样的npm脚本。

In this case you can still use VS Code Launch configs. Instead of using a standard Node Launch process, you add a config that is a “Launch Via NPM” task.

在这种情况下,您仍然可以使用VS Code Launch配置。 您可以使用“通过NPM启动”配置来代替使用标准的节点启动过程。

Now you can add back in your envFile line and tweak the runtimeArgs so that they launch the correct script. This is usually something like “start” or “debug”.

现在,您可以在envFile行中重新添加并调整runtimeArgs以便它们启动正确的脚本。 这通常类似于“开始”或“调试”。

Note that you have to add the --inspect flag to your npm script so that VS Code can attach the debugger. Otherwise the task will launch, but the VS Code debugger will time out like me trying to get a date in high school.

请注意,您必须在npm脚本中添加--inspect标志,以便VS Code可以附加调试器 。 否则,该任务将启动,但是VS Code调试器将像我试图在高中约会那样超时。

生产环境变量 (Production environment variables)

So far we’ve looked at how to define variables for development. You likely won’t use .env files in production, and VS Code Launch Configurations aren’t going to be super helpful on a server.

到目前为止,我们已经研究了如何为开发定义变量。 您可能不会在生产中使用.env文件,并且VS Code启动配置在服务器上不会很有用。

In production, variables will be defined however your platform of choice allows you to do so. In the case of Azure, there are 3 different ways to define and manage environment variables.

在生产中,将定义变量,但是您选择的平台允许您这样做。 对于Azure,有3种不同的方式来定义和管理环境变量。

The first way is to use the Azure CLI.

第一种方法是使用Azure CLI 。

az webapp config appsettings set -g MyResourceGroup -n MyApp --settings PORT=65534

Which works, but, ew.

哪个有效,但是。

Another way is via the Azure web portal. I don’t always use a web portal, but when I do, it’s to set environment variables.

另一种方法是通过Azure Web门户。 我并不总是使用Web门户,但是当我这样做时,它是设置环境变量。

In the case of Azure, these are called “Application Settings”.

对于Azure,这些称为“应用程序设置”。

And since you are using VS Code, you can install the App Service extension and manage all the App Settings right from the editor.

由于使用的是VS Code,因此可以直接从编辑器安装App Service扩展并管理所有App设置。

I love not having to leave VS Code to do anything. I would write emails in VS Code if I could.

我喜欢不必离开VS Code来做任何事情。 如果可以的话,我会用VS Code编写电子邮件。

WAIT A MINUTE!

等一下!

markdown-mail - Visual Studio MarketplaceExtension for Visual Studio Code - Using markdown to write your email and send!marketplace.visualstudio.com

markdown-mail-Visual Studio 代码的 Visual Studio市场 扩展-使用markdown编写电子邮件并发送! marketplace.visualstudio.com

现在你知道了 (Now you know)

Now you know what I know (which aint a lot, let me tell you) and I feel like I accomplished my goal of a tasteful amount of Java jokes along the way. Just in case I didn’t, I’ll leave you with this one.

现在您知道了我所知道的(很多事情,让我告诉您),并且我感觉自己一路实现了一些Java笑话的目标。 以防万一我没有,我会把这个留给你。

Java is a very powerful tool for turning XML into stack traces

Java是将XML转换为堆栈跟踪的非常强大的工具

Java is a very powerful tool for turning XML into stack traces

Java是将XML转换为堆栈跟踪的非常强大的工具

Satire Disclaimer: Most of this is a poor attempt at humor, and some of it at the expense of Java; which isn’t nice but is very easy. These jokes don’t write themselves.

讽刺免责声明:这大部分是对幽默的拙劣尝试,其中一些是以Java为代价的。 不好,但是很容易。 这些笑话不会自己写。

翻译自: https://www.freecodecamp.org/news/heres-how-you-can-actually-use-node-environment-variables-8fdf98f53a0a/

node环境变量

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/7710.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息