当前位置:   article > 正文

node-expand_使用dotenv-expand掌握Node.js上的环境变量

dotenv-expand

node-expand

介绍 (Introduction)

As developers, we found ourselves very often in situations where we need to protect certain data or variables not only from potential attacks but from users as well. When developing a mobile application, a web platform, even a single page application we use to rely on different libraries or third-party services (for instance Google Maps for location, Facebook or Google for signing in, and so on), as well as API credentials (being on our very own server or an external one), and SSH-keys for remote connection. In synthesis, we are speaking of sensitive information.

作为开发人员,我们经常发现自己不仅需要保护某些数据或变量免受潜在攻击,而且还需要受到用户的保护。 在开发移动应用程序,Web平台甚至是单页应用程序时,我们都依赖于不同的库或第三方服务(例如,用于位置的Google Maps,用于登录的Facebook或Google等),以及API凭证(位于我们自己的服务器或外部服务器上)以及用于远程连接的SSH密钥。 综合来说,我们所说的是敏感信息。

To keep our code safe and secure, we can host our code in different repositories, being the most used GitHub, GitLab, and Bitbucket. The recent acquisition of Github by the tech giant Microsoft made most users evaluate the repository they were using, depending on the features they needed and how they felt with each platform. The actual share on providers can be reflected in the following graphic:

为了保持代码的安全性,我们可以将代码托管在最常用的GitHub,GitLab和Bitbucket的不同存储库中。 科技巨头微软公司最近对Github的收购使大多数用户根据他们需要的功能以及每个平台的感受来评估他们正在使用的存储库。 下图显示了提供者的实际份额:

Image for post

什么是环境变量? (What is an Environment variable?)

Environment variables are variables defined in a system that describes your environment. Probably you already used this kind of variables when editing your ~/.bash_profile file, or when you do an export PATH. But these variables are at a system level. We can define all the variables we want there but imagine having multiple applications with their own environment variables, different tools that may require them like Android Studio and Java Development Kit, and even keys and shortcuts you may have defined in the past.

环境变量是在描述您的环境的系统中定义的变量。 编辑〜/ .bash_profile文件或执行导出PATH时,可能已经使用了此类变量 但是这些变量是在系统级别上的。 我们可以在那里定义我们想要的所有变量,但可以想象有多个应用程序具有自己的环境变量,可能需要它们的不同工具,例如Android Studio和Java Development Kit,甚至包括您过去定义的键和快捷方式。

Node.js解决方案 (Solution for Node.js)

Aside from a system level, Node.js offers a solution right out of the box: dotenv. When your Node.js process starts at runtime, it will automatically provide access to all existing environment variables, by creating an object (env from now on) as a property of the process global object.

除了系统级别之外,Node.js还提供了开箱即用的解决方案:dotenv。 当您的Node.js流程在运行时启动时,它将通过创建一个对象(从现在开始为env)作为流程全局对象的属性来自动提供对所有现有环境变量的访问。

You can check your env variables in Node.js typing:

您可以在Node.js中键入以下内容来检查环境变量:

console.log(process.env);

.env文件的重要性 (The importance of a .env file)

Having a .env file on our root folder will not only allow us to manage our variables easier. Making use of gitignore to ignore the files that will be uploaded to the repository, we can hide our .env file to be available only locally, so it won’t be around on your repository.

在我们的根文件夹上有一个.env文件,不仅会使我们更轻松地管理变量。 利用gitignore忽略将要上传到存储库的文件,我们可以隐藏.env文件,使其仅在本地可用,因此它不会出现在您的存储库中。

Let’s say we are working on a Node.js project that includes a MongoDB database connection query, that typically looks like this:

假设我们正在一个Node.js项目中,该项目包含一个MongoDB数据库连接查询,通常如下所示:

db.mongoose.connect(`mongodb://username:password@localhost:27017/my-mongodb-server`, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: true })

In this case, we are exposing our username, password, host with its respective port, and the database name. Exactly all the information one needs to connect remotely to our database and have access to our information.

在这种情况下,我们将公开用户名,密码,带有相应端口的主机以及数据库名称。 确实,一个人需要的所有信息都可以远程连接到我们的数据库并可以访问我们的信息。

The solution suggested is to move all that information to our hidden file, with a key=value format. The convention is to capitalize on the key, and the value should be a string. Create (or modify if existing) a file in your project root folder named .env, with the following content:

建议的解决方案是使用key = value格式将所有信息移动到我们的隐藏文件中。 约定是利用键,并且值应该是字符串。 在项目根文件夹.env中创建(或修改,如果存在)文件,其内容如下:

MONGODB_USERNAME=testuserMONGODB_PASSWORD=testpasswordMONGODB_HOST=localhostMONGODB_PORT=27017MONGODB_SERVERNAME=my-mongodb-server

Now we can update our code to the following:

现在我们可以将代码更新为以下内容:

db.mongoose.connect(`mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_SERVERNAME}`, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: true })

If we added correctly to our .gitignore file the exception for the .env file, this file won’t be pushed to our repository, so if by any chance anyone gets access to our code, the sensitive information won’t be available on code. Remember that our env file is available only in our system. If we push our code to an external server like DigitalOcean or Amazon Web Services, we will need to create the env file there as well in order to be consumed.

如果我们将.env文件的例外情况正确地添加到.gitignore文件中,则该文件将不会被推送到我们的存储库中,因此,如果任何人有机会访问我们的代码,敏感信息将不会在代码中提供。 请记住,我们的env文件仅在我们的系统中可用。 如果我们将代码推送到外部服务器(例如DigitalOcean或Amazon Web Services),则也需要在其中创建env文件以便使用。

A good practice is to create and update a .sample-env file in the source code repository (This one committed and pushed), so you can keep track of which variables you’re using. Otherwise, you will likely end up reading your code a few times to check you’re not missing a single variable.

好的做法是在源代码存储库中创建和更新.sample-env文件(已提交并推送了该文件),因此您可以跟踪所使用的变量。 否则,您可能最终会多次阅读代码,以检查是否没有遗漏任何一个变量。

Another quick example of using simple environment variables is to set the port of an Express.js application. We check if there’s any port set in our .env file; if there’s no port defined, we set the default as 3000:

使用简单环境变量的另一个快速示例是设置Express.js应用程序的端口。 我们检查.env文件中是否设置了端口; 如果未定义端口,则将默认设置为3000:

const PORT = process.env.PORT || 3000;app.listen(PORT, () => {  console.log(`Listening on PORT: ${PORT}`);});

NOTE: This can also be achieved by executing our node application and sending the variables in the same command:

注意:这也可以通过执行节点应用程序并在同一命令中发送变量来实现:

PORT=3001 node server.js# for multiple env variables:PORT=3001 MONGODB_USERNAME=testuser node server.js

The steps described above are, in fact, for the simplest use for environment variables on Node.js. We would need to handle errors for inexisting variables in the .env file, failed loading, etc. For that reason, most developers choose to use the dotenv tool for Node.js.

实际上,上述步骤是最简单地用于Node.js上的环境变量。 我们将需要处理.env文件中不存在的变量,加载失败等错误。因此,大多数开发人员选择对Node.js使用dotenv工具

什么是dotenv? (What is dotenv?)

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env based on The Twelve-Factor App methodology. It features some functionalities like preloading, path configuration, encoding, and more.

Dotenv是一个零依赖模块,它基于The Twelve-Factor App方法将.env文件中的环境变量加载到process.env中。 它具有一些功能,如预加载,路径配置,编码等。

Using it on new or existing projects is as easy as install it with npm or yarn:

在新项目或现有项目上使用它就像使用npm或yarn安装它一样容易:

# With NPMnpm install dotenv# With Yarnyarn add dotenv

简单用法 (Simple Usage)

As The Twelve-Factor App methodology suggests, we should store the environment variables in an app’s config that is likely to vary between deploys, including:

正如“十二要素应用程序”方法所建议的那样,我们应该将环境变量存储在应用程序的配置中,该配置在部署之间可能会有所不同,包括:

  • Resource handles to the database, Memcached, and other backing services

    数据库,Memcached和其他支持服务的资源句柄
  • Credentials to external services such as Amazon S3 or Facebook

    外部服务(例如Amazon S3或Facebook)的凭证
  • Per-deploy values such as the canonical hostname for the deploy

    每次部署的值,例如部署的规范主机名

The simple usage of Dotenv will be requiring and configuring dotenv:

Dotenv的简单用法将要求并配置dotenv:

require('dotenv').config();

Create a .env file in the root directory of your project using the suggested format:

使用建议的格式在项目的根目录中创建一个.env文件:

MY_VALUE=my-key

And we can use it in Node.js with:

我们可以在Node.js中使用它:

console.log(process.env.MY_VALUE);

预加载dotenv (Preloading dotenv)

You can use the — require the command-line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code:

您可以使用-require命令行选项来预加载dotenv。 这样,您无需在应用程序代码中要求并加载dotenv:

node -r dotenv/config your_script.js

利用配置功能 (Making use of the Config feature)

config will read your .env file, parse the content, assign it to process.env, and return an Object with a parsed key containing the loaded content or an error key if it failed.

config将读取您的.env文件,解析内容,将其分配给process.env,并返回一个带有包含已加载内容的解析键的对象,如果失败,则返回一个错误键。

const result = dotenv.config()if (result.error) {  throw result.error}console.log(result.parsed)

The importance of having a config is that we can additionally pass it options. We can set a custom path (Option #1) to specify a custom path when the file is located, we can specify the encoding (Option #2) or we can turn on logging to help debug (Option #3), among other functions.

拥有配置的重要性在于,我们可以另外传递它的选项。 我们可以设置自定义路径(选项1)以在文件定位时指定自定义路径,可以指定编码(选项2),也可以打开日志记录以帮助调试(选项3),以及其他功能。 。

# Option 1require('dotenv').config({ path: '/custom/path/to/.env' });# Option 2require('dotenv').config({ encofing: 'latin1' });# Option 3require('dotenv').config({ debug: process.env.DEBUG });

使用dotenv-expand升级到全部功能 (Upgrade to full functionality with dotenv-expand)

Dotenv-expand is an NPM library that adds variable expansion on top of the dotenv library we used before. It allows us to use dynamic string formats, being able to use a .env file like the following one:

Dotenv-expand是一个NPM库,它在我们之前使用的dotenv库的顶部添加了变量扩展。 它使我们可以使用动态字符串格式,并可以使用.env文件,如下所示:

MONGODB_USERNAME=testuserMONGODB_PASSWORD=testpasswordMONGODB_HOST=localhostMONGODB_PORT=27017MONGODB_SERVERNAME=my-mongodb-serverMONGODB_URI=mongodb://${MONGODB_USERNAME}:${MONGODB_PASSWORD}@${MONGODB_HOST}:${MONGODB_PORT}/${MONGODB_SERVERNAME}

As we can see, we used the username, password, host, port and server name variables to also export a URI variable, concatenating the past strings. This way we can add complexity and dynamic strings.

如我们所见,我们使用了用户名,密码,主机,端口和服务器名称变量来导出URI变量,并连接了过去的字符串。 这样,我们可以添加复杂性和动态字符串。

结论 (Conclusion)

Environment variables exist outside our application’s code, and they are available as soon as our Node.js process boots up. They can be used to decouple our application’s configuration from its code, hide secret API keys, usernames, passwords, and sensitive data, among other functions. It’s helpful when we work on private projects as well as collaborative environments (like work, or an open-source project) when you may want to avoid sharing your database login credentials with other people, or your Github data. And using dotenv-expand we can easily add dynamic strings to make use of the full functionality dotenv has. This was only an introductory tutorial, and the things we can achieve with dotenv can be done in several ways, so feel free to play with this library and see how it can leverage up your code.

环境变量存在于我们应用程序的代码之外,并且它们可以在我们的Node.js进程启动后立即使用。 它们可用于使我们的应用程序的配置与其代码脱钩,隐藏秘密的API密钥,用户名,密码和敏感数据以及其他功能。 当我们可能要避免与其他人共享数据库登录凭据或Github数据时,当我们在私有项目以及协作环境(例如工作或开源项目)上工作时,这将非常有用。 使用dotenv-expand,我们可以轻松添加动态字符串以利用dotenv的全部功能。 这只是一个入门教程,我们可以通过多种方式完成dotenv的工作,因此可以随意使用该库并了解其如何利用您的代码。

翻译自: https://itnext.io/master-environment-variables-on-node-js-with-dotenv-expand-f9724b310bc7

node-expand

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/587240
推荐阅读
相关标签
  

闽ICP备14008679号