Search code examples
node.jsdirectoryenvironment-variables

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?


Solution

  • 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' });