I have a .env
file which is the following:
PORT=5000
I first run source .env
to load the environnement variables.
When I run echo $PORT
, I see that the variable is set to 5000.
But, as soon as I run my nodeJS script, which contains
if(process.env.PORT === undefined) throw new Error("Missing PORT in process.env");
It throws an error because the PORT is undefined.
Even after running the script echo $PORT
is still 5000.
The expected behavior is that process.env.PORT
is 5000
.
2
Answers
as Pointy mentioned it you can pass your environment variable when you start your script.
If you prefer to use a .env file and want to access its variables during will have to install and use the dotenv package.
Two way for doing that.
google research: node js process env
answer source: https://nodejs.dev/en/learn/how-to-read-environment-variables-from-nodejs/
Install the dotenv package and import or require dotenv in your index.js file.
Make sure you restart your server after importing the dotenv config.