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:
This is how i fix my issue
Intially had this in .env of the root of my project
const db_port = 90101
const db_host="localhost"
const db_username="name"
const db_password="pwd"
const db_name="db"
And all my env variables where undefined.
I fixed it by removing all the const and using just key=value insted of const key="value"
db_port = 90101
db_host=localhost
db_username=name
db_password=pws
db_name=db
I had the same problem. I realized my file was somehow encoded in UCS-2 BE BOM
. Converting my .env
file to UTF-8
fixed it (you can easily do that using Notepad++, for example).
Make sure that variables are not already set. Dotenv won't override them.
If variables are set then you will have to remove them. In powershell you can use the following command - as mentioned here:
Remove-Item Env:\MyTestVariable
I had the same problem and I tried 4 hours to find the fault. In my case, it was bizarre.
When I tried "node app.js", it worked. When I wanted a daemon to start it, it did not work.
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')})
is dotenv installed in your project?
Try to install it using npm install dotenv
in your project.
Once it is installed load it in any files where you need it using const env = require('dotenv').config()
.
You can then use in any line where you need to. For example to call port from .env use: process.env.PORT
const dotenv = require('dotenv'),
path = require('path')
dotenv.config({path: path.join(__dirname, '../.env')})