nexus186
nexus186

Reputation: 127

How to run node app from sub-directory with .env variables of that sub-directory?

I have a Node.js App called app.js and its stored in the directory B.

To run this script correctly it needs enviroment variables. These are stored in a file called .env, which is also in directory B.

In my app.js the env-variables are loaded via require("dotenv").config(); and I can then access them with e.g. process.env.SOME_VAR

So if I am currently located in directory B, I can just use node app and my app will execute just fine.

But if I go to the parent directory A and try to run my app via

node ./B/app

it will not execute, because it seems to have no access to the enviroment variables of the .env file.

So, my question is, how can I run my script from its parent folder, if I want to keep the .env file in the same directory?

Upvotes: 11

Views: 11095

Answers (3)

Abdallah Ismail
Abdallah Ismail

Reputation: 1

Brilliant! it worked for me, I put my .env inside /vars folder and used this line

require('dotenv').config({path : 'vars/.env'});

Instead of this line

require("dotenv").config();

Upvotes: 0

Mamunur Rashid
Mamunur Rashid

Reputation: 41

you can set path using {path : '../.env'}.

require('dotenv').config({path : '../.env'});

Upvotes: 3

toonday
toonday

Reputation: 571

You could use dotenv to load the the content of the environment variable i.e.

const dotenv = require('dotenv');

// ...

// Then go ahead to load the .env file content into process.env
dotenv.config({ path: '/full/custom/path/to/your/env/vars' });

Upvotes: 21

Related Questions