Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dotenv file is not loading environment variables

I have .env file at root folder file

NODE_ENV=development NODE_HOST=localhost NODE_PORT=4000 NODE_HTTPS=false DB_HOST=localhost DB_USERNAME=user DB_PASSWORD=user 

And server.js file in the root/app/config/server.js folder. The first line of server.js file is

require('dotenv').config();

I also tried following:

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

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

However, my env variable are not loaded when I run the server.js file from command prompt

node root/app/config/server.js

If I use the visual studio and press F5, it loads!!

I'm not sure what I'm doing wrong, what I'm missing. Any suggestion is highly appreciate. Thanks.

like image 923
ANewGuyInTown Avatar asked Feb 20 '17 01:02

ANewGuyInTown


People also ask

How do you preload dotenv?

Preload. You can use the --require ( -r ) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. Additionally, you can use environment variables to set configuration options.

Can I use variables in .env file?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.

How do you use variables in dotenv?

Once you have DotEnv installed and configured, make a file called . env at the top level of your file structure. This is where you will create all of your environment variables, written in thr NAME=value format. For example, you could set a port variable to 3000 like this: PORT=3000 .

Can not find module dotenv?

To solve the error "Cannot find module 'dotenv'", make sure to install the dotenv package by opening your terminal in your project's root directory and running the following command: npm install dotenv and restart your IDE and development server.


2 Answers

How about use require('dotenv').config({path:__dirname+'/./../../.env'}) ?

Your problem seems to be the execution path.

like image 115
Yonghoon Lee Avatar answered Oct 10 '22 02:10

Yonghoon Lee


This solved my issues in Node v8.14.1:

const path = require('path') require('dotenv').config({ path: path.resolve(__dirname, '../.env') }) 

Simply doing require('dotenv').config({path:__dirname+'/./../../.env'}) resulted in a location that resolved as /some/path/to/env/./../../.env

like image 31
DavidP Avatar answered Oct 10 '22 03:10

DavidP