I am trying to use dotenv to manage configurations for different environment. At the moment, I only have development environment. To test dotenv library, I have .env
and .env.development
files in the root folder.
In .env
, I have
PORT=5001
In .env.development
, I have
PORT=5002
In index.js
, if I have require('dotenv').config()
, .env
file is loaded and I can see process.env.PORT
is 5001.
If I have require('dotenv').config({path: '.env.'+process.env.NODE_ENV})
, and I also have NODE_ENV=development node index.js
, then .env.development
is not loaded.
However, if I have require('dotenv').config({path: '.env.development'})
, .env.development
file is loaded correctly.
Can I please get some help? Thank you
Update
The test code I am having is
const dotenv = require('dotenv');
const environment = process.env.NODE_ENV || 'development';
console.log(environment);
const dotenvPath = '.env.'+environment;
console.log(dotenvPath);
dotenv.config({path: dotenvPath});
console.log(process.env.PORT);
console.log(process.env.NODE_ENV);
and I am in Windows.
When I run set NODE_ENV=development & node index.js
, the console log is
In CMD:
D:\>set NODE_ENV=development & node index.js
development
.env.development
undefined
development
In Powershell, it is correct.
PS D:\> $env:NODE_ENV='development'; node index.js
development
.env.development
5001
development
I guess when I put the command as script in package.json, the command is run in CMD, rather than in Powershell, even though I run npm run start:development
in Powershell.
Finally, I find the reason.
The way I debug it is to have dotenv.config({path: dotenvPath, debug: true});
in my code and then when I run set NODE_ENV=development & node index.js
in CMD, I get
development
.env.development
[dotenv][DEBUG] Failed to load .env.development ENOENT: no such file or directory, open '.env.development '
undefined
development
I notice the space in the file name, which leads to the .env.development
could not be found.
Then I change the command to set NODE_ENV=development&node index.js
, then it starts working.
development
.env.development
5001
development