How to Create and Use .env File in Node JS?

By Hardik Savani May 14, 2021 Category : Node JS

Hi,

In this post, we will learn how to create .env file in node js. this example will help you how to use .env file in node js. Here you will learn node js .env file example. This article will give you simple example of node js environment configuration file.

In this simple example we will create .env file for environment configuration variable like port, app name, database configuration etc. we will use dotenv npm package for setup .env file variable.

Let's see simple example bellow:

Create Node App:

mkdir my-request-app

cd my-request-app

npm init

Install dotenv:

npm install dotenv

Create File: server.js

const dotenv = require('dotenv');

dotenv.config();

console.log(`Your App Name is ${process.env.APP_NAME}`);

console.log(`Your App Environment is ${process.env.APP_ENV}`);

console.log(`Your App Port is ${process.env.APP_PORT}`);

Run App:

node server.js

Output:

Your App Name is Laravel

Your App Environment is local

Your App Port is 8000

i hope it can help you...

Tags :
Shares