简体   繁体   中英

.env file not being recognized when trying to read from a file within a folder instead of root in NodeJS

In my NodeJS app, I have.env file in root directory with following info:

NODE_ENV = development
PORT = 3002
#db credentials
dbURL = 'mongodb+srv://username:password@clusterName-0gcm3.mongodb.net/dbName?retryWrites=true&w=majority'

And in the root directory I also have config file (config.js) which grabs the variables:

const dotenv = require('dotenv');
dotenv.config();

module.exports = {
  port: process.env.PORT,
  dbURL: process.env.dbURL
}

In my App.js which is again in root folder I am able to successfully read this file and able to connect with DB:

const express = require('express');
const mongoose = require('mongoose');
const { port, dbURL } = require('./config');  //reading the config file and grabbing the vars
const app = express();

app.use(express.json());

//works well!
mongoose.connect(dbURL, { useUnifiedTopology: true, useNewUrlParser: true})
        .then(res => {
          console.log(`Listening on port ${port}`);
          app.listen(port);
        })
        .catch(err => console.error(err));

Now I am trying to write some standalone scripts to populate the DB with some sample data and in that script I am trying to connect to DB seperately as those scripts will only be executed with node <file> command. This file (dbPopulate.js) is located within /helper-scripts/ folder. And the script looks like this:

const express = require('express');
const mongoose = require('mongoose');
const {port, dbURL} = require('../config'); //attempting to read config.js that calls the .env file

const app = express();
app.use(express.json());


console.log(dbURL, port) //throws undefined for both vars
mongoose.connect(dbURL, { useUnifiedTopology: true, useNewUrlParser: true})
        .then(res => {
          console.log(`Listening on port ${port}`);
          app.listen(port);
        })
        .catch(err => console.error(err));

Just to make it clear this is my file structure:

/.env
/app.js
/config.js
/helper-scripts/dbPopulate.js  (culprit)

UPDATE for displaying error log:

When I execute dbPopulate.js standalone I get following errors:

$ node dbPopulate.js
undefined undefined
C:\teamSIO\server\node_modules\mongoose\lib\connection.js:582
    throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
    ^

MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
    at NativeConnection.Connection.openUri (C:\teamSIO\server\node_modules\mongoose\lib\connection.js:582:11)
    at Mongoose.connect (C:\teamSIO\server\node_modules\mongoose\lib\index.js:335:15)
    at Object.<anonymous> (C:\teamSIO\server\helper-scripts\dbPopulate.js:30:10)
    at Module._compile (internal/modules/cjs/loader.js:1123:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
    at Module.load (internal/modules/cjs/loader.js:972:32)
    at Function.Module._load (internal/modules/cjs/loader.js:872:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

I would try using an array instead of an object.

require('dotenv').config();
const port = process.env.PORT;
dbURL: process.env.dbURL;
module.exports = [
    port,
    dbURL
];

and to use

const [port, dbURL] = require('./config');

Also, I don't think that this was the error, but you do have two dots in your "dbPopulate.js" const {port, dbURL} = require('../config'); file, this might be your problem

It's been a long time since you asked, but maybe my answer will help someone else.

When you execute node dbPopulate.js from directory helper-scripts the function require will be able to correctly load ../config , but that in turn will fail to find the file .env because it expects to find it at the same level, from a file/directory hierarchy perspective.

You can either copy .env inside helper-scripts , which you'd better not, or execute dbPopulate.js from project's root directory.

when u run a node app where the.env file is not in the same relative location as the file u are running then u need to specify the correct path for the.env file. Example if i have app.js and.env file both inside the same project folder location then when I'll do node app.js, then just dotenv.config() will work fine as its default path is

process.cwd() + '.env'

but for say i have a file inside seeder/chat-message-type.seeder.js then to read the.env file which is outside i have to go out one directory.

const path = require("path")

// have to modify dotenv file path becuase the app is run from seeder folder
dotenv.config({ path: path.join(process.cwd(), "..", ".env") })

This will ensure that whenever i am reading the.env file by running

cd seeder
node chat-message-type.seeder.js 

it will still load all the data from.env file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM