Skip to content
Advertisement

dotenv process.env variable undefined in globally installed custom CLI tool

I’m migrating one of my CLI tools over to a global installation so that it can be installed globally and used anywhere on my system. Most of my src files include require('dotenv').config() at the top of them, but for some reason the env is undefined now that it’s installed globally.

What am I missing?

My package JSON looks like:

{
  "name": "scoop",
  "version": "1.9.0",
  "main": "bin/scoop.js",
  "dependencies": {
    "axios": "0.20.0",
    "cli-spinners": "2.4.0",
    "commander": "6.1.0",
    "dotenv": "8.2.0",
    "log-symbols": "4.0.0",
    "ora": "5.1.0",
    "readline": "1.3.0"
  },
  "bin": {
    "scoop": "./bin/scoop.js"
  }
}

bin/scoop.js then contains the following at the top:

#!/usr/bin/env node

require('dotenv').config();
const forms = require('../src/utils/LocateForms');
...

And I’m loading in additional JS src files that are exported, I’ve got an .env in my project my my custom variables just come up as undefined now?

Advertisement

Answer

I think it’s expected behaviour.

The default path value for dotenv is Default: path.resolve(process.cwd(), '.env') according to the GitHub readme.

Now process.cwd changes depending upon from where you execute the executable file. For example if u start node /a/b/c.js then the cwd would be /a/b and if you start it from node /a/b/d/c.js the cwd would be /a/b/d.

So, in order to get the the .env file that you want either you have to store the .env file in a common area like ~/.yourenv like most other executables do(think .bashrc).

Or, you can try to get the installation folder and get the .env file using an absolute path.

For example you can try to import npm and get the prefix to find out the installation folder.

var npm = require("npm")
npm.load({}, function (er) {
    if (er) return handleError(er)
    console.log(npm.get('prefix'));
})

Or, you can use some package like https://www.npmjs.com/package/get-installed-path

Advertisement