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.
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.
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.
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 .
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.
How about use require('dotenv').config({path:__dirname+'/./../../.env'})
?
Your problem seems to be the execution path.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With