Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

environment variables - How do I setup the dotenv file in Node.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');

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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. The filename should be .env (I believe .env.test is also acceptable).

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...