Home > Enterprise >  DotEnv comments are crashing
DotEnv comments are crashing

Time:04-29

I'm using dotenv version 16.0.0 in my NodeJS project but the comment feature that was recently added causes a crash. Without the comments the .env file works perfectly, loading values from it.

The .env file content:

# Print out information during runtime, useful for debugging problems not caught. 
(true/false)
VERBOSE=false

# Database settings, update for actual deployment environment
DB_USERNAME=postgres
DB_PASSWORD=TINY_DUCK
DB_NAME=user_database
DB_HOST=localhost
DB_PORT=5432

The command to run the NodeJS project is:

mocha -r .env ./tests/testManager.js --exit

And the error message I get when running the NodeJS project:

× ERROR: C:\Users\thega\Source\Repos\network\.env:1
# Print out information during runtime, useful for debugging problems not caught. (true/false)
^

SyntaxError: Invalid or unexpected token
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at exports.requireOrImport (C:\Users\thega\source\repos\network\node_modules\mocha\lib\nodejs\esm-utils.js:60:20)
    at async exports.handleRequires (C:\Users\thega\source\repos\network\node_modules\mocha\lib\cli\run-helpers.js:94:28)
    at async C:\Users\thega\source\repos\network\node_modules\mocha\lib\cli\run.js:353:25

CodePudding user response:

It looks to me as if you are trying to import the .env file as JS module instead of loading it with the dotenv package.

The -r flag to mocha means "require":

This will require a module before loading the user interface or test files.

It is useful for:

  • Test harnesses
  • Assertion libraries that has augment built-ins or global scope (such as should.js)
  • Instant ECMAScript modules using esm
  • Compilers like Babel via @babel/register or TypeScript using ts-node (using --require ts-node/register).

So it will try to load the file as JavaScript and of course that can't work.

Instead, you can require dotenv/config so it will parse the file for you and update process.env accordingly:

mocha -r dotenv/config ./tests/testManager.js --exit

Or, if you already do require('dotenv').config() in your code, you don't need any -r switch here at all.

  • Related