在 Node JS 模块中使用 dotenv

Using dotenv in a Node JS module

我正在构建一个 Node 应用程序,它 returns 使用 Google 自定义搜索引擎 (CSE) 的搜索结果。

我将把发送请求到 Google 和 returns 结果的应用程序部分分离到一个模块中。

我已经在应用程序中使用 dotenv 来存储 MongoDB 凭据和应用程序的 URL。

我还想在模块中使用 dotenv 来存储 Google CSE ID 和 CSE 的 API 密钥。

我希望我的模块独立于主应用程序工作,但当它是一个模块时也使用主应用程序的 dotenv 文件。

目前我的模块结构如下所示:

module
 |
 +-- node_modules
 |  |
 |  \-- dotenv
 |     |
 |     \-- (dotenv module's files....)
 |
 +-- .env
 |
 \-- index.js

它可以单独使用。 .env 文件存储所需的环境变量,我可以通过要求 dotenv 模块在 index.js 文件中访问它们。

当包含在主应用程序中时,结构如下所示:

app
 |
 +-- node_modules
 |  |
 |  +-- dotenv
 |  |  |
 |  |  \-- (dotenv module's files....)
 |  |
 |  \-- my_google_search_module
 |     |
 |     +-- node_modules
 |     |  |
 |     |  +-- dotenv
 |     |     |
 |     |     \-- (dotenv module's files...)
 |     |
 |     \-- index.js
 |
 +-- .env
 |
 \-- index.js

这也行。我将所有环境变量存储在主应用程序的 .env 文件中,并且通过在应用程序的 index.js 中要求 dotenv 我可以访问这些变量。另外,"my_google_search_module" 似乎正在从应用程序根目录中的 .env 文件中提取所需的变量。模块中没有.env文件。

我的问题是我这样做的方式正确吗?

我对此进行了进一步研究,可以确认模块的 .env 正在从应用程序的 .env 文件中提取所需的环境变量。

我相信 dotenv 自述文件中的这一部分虽然不完全相关,但可以验证 - https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set

We will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.

是的,你做得对。整个项目中必须有一个 .env 文件。但是有一个技巧可以将它包含在不同的目录结构中。 例如: 您的 index.js 文件位于 /app/src,您的 .env 文件位于 /app。您的 index.js 文件有这个

dotenv.config({路径: "../.env"});

你也可以使用 dotenv.config({path: path.join(__dirname, "../.env")});

对于节点项目,我建议使用 npm 包 dotenv。您可以找到有关如何使用它的详细信息。不要忘记在项目文件的开头包含 require('dotenv').config(),例如 index.js.

现在您可以在任何需要的地方使用 .env 内容。例如,我希望我的服务器端口为 4000,我在 .env 中将其定义为 PORT=4000。现在,要在任何地方使用 .env 变量,只需在后缀中提供变量名称,例如 process.env.PORT。这就对了。虽然我迟到了 post,但希望这能对您有所帮助。