Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment withing .env file

I have one .env file , that looks like :

NODE_ENV = local
PORT = 4220
BASE_URL = "http://198.**.**.**:4220/"

PROFILE_UPLOAD = http://198.**.**.**:4220/uploads/profile/
POST_UPLOAD = http://198.**.**.**:4220/uploads/discussion/
COMPANY_UPLOAD = http://198.**.**.**:4220/uploads/company/
ITEM_UPLOAD  = http://198.**.**.**/uploads/item/
GROUP_UPLOAD  = http://198.**.**.**/uploads/group/

I want to do something like this :

NODE_ENV = local
IP = 198.**.**.**
PORT = 5000
BASE_URL = http://$IP:$PORT/

PROFILE_UPLOAD = $BASE_URL/uploads/profile/
POST_UPLOAD = $BASE_URL/uploads/discussion/
COMPANY_UPLOAD = $BASE_URL/uploads/company/
ITEM_UPLOAD  = $BASE_URL/uploads/item/
GROUP_UPLOAD  = $BASE_URL/uploads/group/

Expected result of BASE_URL is http://198.**.**.**:4220/

I have tried many few syntax but not getting computed values

Tried Syntax : "${IP}" , ${IP} , $IP

I have used dotenv package , for accessing env variables.

like image 376
Vivek Doshi Avatar asked Feb 14 '18 07:02

Vivek Doshi


People also ask

Can I use variables in .env file?

You can set default values for environment variables using a .env file, which Compose automatically looks for in project directory (parent folder of your Compose file). Values set in the shell environment override those set in the .env file.

How do you use variables in DotEnv?

For example, you could set a port variable to 3000 like this: PORT=3000 . There is no need to wrap strings in quotation marks. DotEnv does this automatically for you. Once you've created this file, remember that you should not push it to GitHub as it can contain sensitive data like authentication keys and passwords.

What should .env files contain?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file.


1 Answers

dotenv-expand is the solutions as @maxbeatty answered , Here are the steps to follow

Steps :

First Install :

npm install dotenv --save
npm install dotenv-expand --save

Then Change .env file like :

NODE_ENV = local
PORT = 4220
IP = 192.***.**.**
BASE_URL = http://${IP}:${PORT}/

PROFILE_UPLOAD = ${BASE_URL}/uploads/profile/
POST_UPLOAD = ${BASE_URL}/uploads/discussion/
COMPANY_UPLOAD = ${BASE_URL}/uploads/company/
ITEM_UPLOAD  = ${BASE_URL}/uploads/item/
GROUP_UPLOAD  = ${BASE_URL}/uploads/group/

Last Step :

var dotenv = require('dotenv');
var dotenvExpand = require('dotenv-expand');

var myEnv = dotenv.config();
dotenvExpand(myEnv);

process.env.PROFILE_UPLOAD; // to access the .env variable

OR (Shorter way)

require('dotenv-expand')(require('dotenv').config()); // in just single line
process.env.PROFILE_UPLOAD; // to access the .env variable
like image 51
Vivek Doshi Avatar answered Nov 02 '22 00:11

Vivek Doshi