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

查看:573
本文介绍了如何在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,但是当我尝试在控制台中输出该值时,我得到的错误是undefined.

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 the error that it is undefined.

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

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

推荐答案

对于我来说,每次我尝试使用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.

这是故障排除列表:

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

使用此语句require('dotenv').config();

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

The .env file should be in the root directory of your project.

遵循DB_HOST=localhost之类的文件编写规则",无需将值用双引号或单引号引起来.

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

此外,请在NPM网站上查看软件包的文档.

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

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

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