Hello Developers, I think we all are the use of the many third party libraries, APIs, or something other environments for the make our work easier
Sometimes that all working tools required some configurations to manage the working flow of the app engine. So, there are developing issues to be how to manage these configurations in the app.
in nodeJS environment that makes an easier to use .env files.
So, Lets Build an Demo to show how can we use .env file configs into our node environment.
- Creating a Project
$ mkdir node-env-demo
$ cd node-env-demo
$ npm init
- Installing Dependencies using npm
$ npm install express dotenv
Here we are using 2 Dependencies
1. Express
2. dotenv
- Create .env file and write the following.
myServerToken = abcdefghi12345
Here we have create an environment variable named myServerToken
and set the value as a some random string.
- Create an app.js file and put following code into it.
var app = require("express")();var env = require("dotenv").config();app.get("/", (req, res) => { res.send(process.env.myServerToken);});app.listen(3000, () => console.log("Server Listen at 3000"));
Here we are using dotenv
package to load our .env
file to access environment variables in our node app.
The dotenv package require(“dotenv”).config()
load the .env file into proecess.env
.
Let be testing our app to open your terminal or windows and run the command node app.js
and open the browser and goto localhost:3000
.

That’s Done.
in node.js environment .env
is used to store global config like database configuration such as username, database-name etc…
Comments
Post a Comment