如何在 Node.js 中设置 dotenv 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26973484/
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 18:08:13  来源:igfitidea点击:

How do I setup the dotenv file in Node.js?

node.jsenvironment-variables

提问by user3775998

I am trying to use the dotenvNPM package and it is not working for me. I have a file config/config.jswith the following content:

我正在尝试使用dotenvNPM 包,但它对我不起作用。我有一个config/config.js包含以下内容的文件:

'use strict';

var dotenv = require('dotenv');
dotenv.load();
console.log('config');

I have another file .envat the root of my application folder. I also have an environment variable TWILIO_ACCOUNT_SID.

.env我的应用程序文件夹的根目录中有另一个文件。我也有一个环境变量TWILIO_ACCOUNT_SID

This is the process I go through while trying to use the environment variables in a certain function:

这是我尝试在某个函数中使用环境变量时所经历的过程:

$ node
> require('./config/config.js');
config
{}
> process.env.TWILIO_ACCOUNT_SID
undefined

I defined the TWILIO_ACCOUNT_SIDin my .envfile but as soon as I try to output the value in my console, I get the error that it is undefined.

TWILIO_ACCOUNT_SID在我的.env文件中定义了,但是一旦我尝试在控制台中输出该值,我就会收到错误消息,它是undefined.

If you have any suggestions on how to troubleshoot this problem that will be very much appreciated.

如果您对如何解决此问题有任何建议,我们将不胜感激。

回答by Basheer AL-MOMANI

In my case, every time I tried to get a key from the .envfile using process.env.MY_KEY, it returned undefined.

就我而言,每次我尝试.env使用从文件中获取密钥时process.env.MY_KEY,它都会返回undefined.

I suffered from this problem for two hours just because I named the file something like keys.envwhich is not considered to be a .envfile.

我被这个问题困扰了两个小时,只是因为我将文件命名keys.env为不被认为是.env文件的名称。

So here is the troubleshooting list:

所以这里是故障排除列表:

  1. The filename should be .env(I believe .env.testis also acceptable).

  2. Make sure you are requiring it as early as possiblein your application using this statement require('dotenv').config();

  3. The .envfile should be in the root directoryof your project.

  4. Follow the "file writing rules" like DB_HOST=localhost, no need to wrap values in double/single quotes.

  1. 文件名应该是.env(我相信.env.test也是可以接受的)。

  2. 使用此语句确保您在应用程序中尽早要求它require('dotenv').config();

  3. .env文件应位于项目的根目录中。

  4. 遵循“文件写入规则”之类的DB_HOST=localhost,无需将值括在双引号/单引号中。

Also, check the documentation of the package on the NPM site.

另外,请检查NPM 站点上的包文档

回答by teliz

I solved this using:

我使用以下方法解决了这个问题:

require('dotenv').config({path: __dirname + '/.env'})

or with an absolute path:

或使用绝对路径:

C:\asd\auhsd\.env

If it does not find the .envfile, it will return undefined.

如果没有找到该.env文件,它将返回undefined.

回答by user3006381

Save yourself some troubleshooting time and log your require call, like so:

为自己节省一些故障排除时间并记录您的需求调用,如下所示:

console.log(require('dotenv').config())

You should see an error with more detailed info on the problem.

您应该会看到一个错误,其中包含有关该问题的更详细信息。

回答by unplugged

Had the same issue recently. Check your .envfile and use equal sign not colon. Here's an example:

最近有同样的问题。检查您的.env文件并使用等号而不是冒号。下面是一个例子:

key=value

instead of:

代替:

key:value

回答by Antoine Boisier-Michaud

I had the same problem. I realized my file was somehow encoded in UCS-2 BE BOM. Converting my .envfile to UTF-8fixed it (you can easily do that using Notepad++, for example).

我有同样的问题。我意识到我的文件以某种方式编码为UCS-2 BE BOM. 将我的.env文件转换为UTF-8修复它(例如,您可以使用 Notepad++ 轻松完成此操作)。

回答by user3775998

i didn't put my environment variables in the right format as was in the dotenv module documentation e.g. i was doing export TWILIO_CALLER_ID="+wwehehe" and so the dotenv module wasn't parsing my file correctly. When i noticed that i removed the export keyword from the declarations and everything worked fine.

我没有像 dotenv 模块文档中那样以正确的格式放置我的环境变量,例如我在做 export TWILIO_CALLER_ID="+wwehehe" ,所以 dotenv 模块没有正确解析我的文件。当我注意到我从声明中删除了 export 关键字并且一切正常时。

回答by Korte

Make sure that variables are not already set. Dotenv won't override them.

确保尚未设置变量。Dotenv 不会覆盖它们。

If variables are set then you will have to remove them. In powershell you can use the following command - as mentioned here:

如果设置了变量,则必须删除它们。在 powershell 中,您可以使用以下命令 -如此处所述

Remove-Item Env:\MyTestVariable

回答by ndsvw

I had the same problem and I tried 4 hours to find the fault. In my case, it was bizarre.

我遇到了同样的问题,我尝试了 4 个小时来查找故障。就我而言,这很奇怪。

When I tried "node app.js", it worked. When I wanted a daemon to start it, it did not work.

当我尝试“node app.js”时,它起作用了。当我想要一个守护进程启动它时,它不起作用。

How did I solve my problem? I replaced:

我是如何解决我的问题的?我替换了:

var dotenv = require('dotenv');
dotenv.load();

with:

和:

var dotenv = require('dotenv').config({path: path.join(__dirname, '.env')})

回答by Ahmed Jehanzaib

Make sure to set cwd in the pm2 config to the correct directory for any calls to dotenv.config().

确保将 pm2 配置中的 cwd 设置为对 dotenv.config() 的任何调用的正确目录。

Example: Your index.js file is in /app/src, your .env file is in /app. Your index.js file has this

示例:您的 index.js 文件在 /app/src 中,您的 .env 文件在 /app 中。你的 index.js 文件有这个

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

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

Your pm2 json config should have this: "cwd": "/app/src", "script": "index.js"

你的 pm2 json 配置应该是这样的: "cwd": "/app/src", "script": "index.js"

You could also use dotenv.config({path: path.join(__dirname, "../.env")}); to avoid the CWD issue. You will still have a problem if you move the .env or the index.js file relative to each other.

你也可以使用 dotenv.config({path: path.join(__dirname, "../.env")}); 以避免CWD问题。如果将 .env 或 index.js 文件相互移动,您仍然会遇到问题。

回答by Knowledge

Take care that you also execute your Node script from the ROOTfolder.

注意您还从ROOT文件夹执行 Node 脚本。

E.g. I was using a testing script in a subfolder called ./bin/test.js. Calling it like: node ./bin/test.jsworked totally fine. Calling it from the subfolder like:

例如,我在名为./bin/test.js. 称之为:node ./bin/test.js工作完全正常。从子文件夹调用它,如:

$ pwd
./bin
$ node ./test.js

causes dotenvto not find my ./.envfile.

导致dotenv找不到我的./.env文件。