28-Jul-2022
.
Admin
Hello Friends,
This tutorial is focused on node js get environment variable. you can understand a concept of nodejs get environment variable or default. I would like to share with you how to get env variable in node js. This tutorial will give you simple example of how to get environment variables in node js.
In this post, the example is how to get environment variables in Node JS?. if you need to add an environment variable in the .env file and need to access the .env variable in node js then I will help you with how to get the environment variable in Node JS. It is use to process.env to access all .env variable in js file.
So, let's see the below solution with an example:
Step 1 : Install Node JS
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
Step 2 : Install dotenv Package
Now, in this step use the dotenv package install get environment variables .env file.
npm install dotenv
Step 3 : Create .env File
If you have multiple environment variables in your node project, you can also create an .env file in the root directory of your project.
.env
# .env file
ENV_MESSAGE="Hello Welcome to Nicesnippets.com"
Step 4 : Add Code index.js File
here, we need to create index.js file and add this code.
index.js
require('dotenv').config();
console.log(process.env.ENV_MESSAGE);
Run Node JS App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Node JS app:
node index.js
Output:
Hello Welcome to Nicesnippets.com
It will help you...
#Node JS