goplay
goplay

Reputation: 154

Dotenv not loading env variables with correct path

I'm using the dotenv library, but my env variables returns undefined

Here is app.ts:

require('dotenv').config({path: '/.env'});
console.log(process.env.MAIN_DB_PATH) // returns undefined

Here is my .env file:

MAIN_DB_PATH=./data/database.db
UPLOAD_MULTER_DIR=./module/car/uploads

My folder structure is

enter image description here

So it should works fine :(

Upvotes: 4

Views: 11288

Answers (3)

Stanley Ulili
Stanley Ulili

Reputation: 1364

If you have Node.js 20.6.0 or higher, the functionality is buit-in and you don't have to use the dotenv package anymore.

With the .env file in your directory:

MAIN_DB_PATH=./data/database.db
UPLOAD_MULTER_DIR=./module/car/uploads

You can set these variables as environment variables with --env-file option:

node --env-file .env index.js

You can then access the environment variables from the process.env object:

console.log(process.env.MAIN_DB_PATH)  

Running the file yields the following:

// Output
./data/database.db

Upvotes: 0

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

To load the .env file in a different directory, you need to provide the absolute path to that file.

  • __dirname : the absolute path to the directory of the file where you need to load .env file (app.ts in this case)
  • .. : go 1 level up

Then path.resolve will give you the absolute path to .env file

const path = require('path');
require("dotenv").config({ path: path.resolve(__dirname, '..', '.env') });
console.log(process.env.MAIN_DB_PATH);

Upvotes: 6

Zavael
Zavael

Reputation: 2468

You do not need path if the .env file is at the root, but you can define a return value from config method and check if error happend

const result = dotenv.config()

if (result.error) {
  throw result.error
}

console.log(result.parsed)

source: https://www.npmjs.com/package/dotenv config paragraph

Upvotes: 7

Related Questions