javascript – Node JS, Dotenv variable undefined inside other directory rather than root

Here is my project structure:

\root
 +- \src\helper
 | +- mongoCon.js
 +- .env

Inside the .env I have:

DB_CONN_STRING=somestring

Inside mongoCon.js:


const { MongoClient, ServerApiVersion } = require('mongodb');
require('dotenv').config();

const connString = process.env.DB_CONNECTION_STRING;

// Create a MongoClient with a MongoClientOptions object to set the Stable API version
// const client = new MongoClient(connString, {
//     serverApi: {
//       version: ServerApiVersion.v1,
//       strict: true,
//       deprecationErrors: true,
//     }
//   });


console.log(connString)

This is returning undefined and I don’t know why.

When I put the mongoCon.js on root level the code runs as intended.
I think the problem is related to the path, but I’m not used to js.

Read more here: Source link