如何在 Node.js 中设置 dotenv 文件? [英] How do I setup the dotenv file in Node.js?

查看:22
本文介绍了如何在 Node.js 中设置 dotenv 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 dotenv NPM 包,但它不适合我.我有一个文件 config/config.js 包含以下内容:

I am trying to use the dotenv NPM package and it is not working for me. I have a file config/config.js with the following content:

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

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

I have another file .env at the root of my application folder. I also have an environment variable 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

我在 .env 文件中定义了 TWILIO_ACCOUNT_SID,但是当我尝试在控制台中输出该值时,我收到一条错误消息,指出该变量未定义.

I defined the TWILIO_ACCOUNT_SID in my .env file but as soon as I try to output the value in my console, I get an error stating that the variable is undefined.

我将非常感谢您在解决此问题时提供的任何支持.

I will be very grateful for any support in troubleshooting this issue.

推荐答案

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

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

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

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

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

So here is the troubleshooting list:

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

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

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

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

遵循 DB_HOST=localhost 等文件写入规则",无需将值用双引号/单引号括起来.

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

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

这篇关于如何在 Node.js 中设置 dotenv 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆