Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dotenv package fails to load environment variables when CLI is executed outside project directory #831

Open
mathiasgheno opened this issue Jun 22, 2024 · 2 comments

Comments

@mathiasgheno
Copy link

Not sure if this is a bug. You can access the minimal reproduction repository here. In the README.md of the repo there is the explanation. Putting bellow for historical purpose.

Context

Want to create a local CLI that use dotenv package.

Steps to reproduce

npm link

Consider you will have access to the CLI dotenv_bin_load from your terminal.

Inside the folder of the project, run:

dotenv_bin_load

You will get the ACCESS_TOKEN normally.

Now, run the same command outside the folder of the project.

cd ..
dotenv_bin_load

You will not get the ACCESS_TOKEN.

Working Solution

Using the common.js config and renaming the .js to .mjs and using the path resolve to find the .env file.

#! /usr/bin/env node

const path = require('path');
const baseDir = path.resolve(__dirname, '../');
const envPath = path.join(baseDir, '.env');

require('dotenv').config({path: envPath});
console.log(process.env.ACCESS_TOKEN);
@motdotla
Copy link
Owner

hi @mathiasgheno, cool idea.

have you seen https://github.com/dotenvx/dotenvx ?

will it do what you need here?

@mathiasgheno
Copy link
Author

Hello @motdotla, not yet.

I'll study it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants