Search code examples
node.jsdotenv

My environment variable comes up undefined


I'm not sure why my environment variable comes up undefined. This is the first time I am using environment variables and can not seem to figure out what the issue is,

My environment file is something like this:

# ANSIBLE MANAGED FILE, YOUR CHANGES WILL BE LOST!
PORT=3001
NODE_ENV=development

# PostgreSQL
MY_DATABASE_CLIENT: 'pg'
MY_DATABASE_HOST: '127.0.0.1'

and my model contains these two lines:

require('dotenv').config({path: '/opt/eosapi/.env'});

console.log("ENV VARIABLE CHECK...",process.env.MY_DATABASE_CLIENT);

however whenever I run this file, I get:

ENV VARIABLE CHECK... undefined

Could anyone point out the issue to me?


Solution

  • Try removing the absolute path

    require('dotenv').config();
    

    And then debug using

    const result = require('dotenv').config()
    
    if (result.error) {
      throw result.error
    }
    
    console.log(result.parsed)
    

    Use proper assingment

    # ANSIBLE MANAGED FILE, YOUR CHANGES WILL BE LOST!
    PORT=3001
    NODE_ENV=development
    
    # PostgreSQL
    MY_DATABASE_CLIENT='pg'       # <--------- must be =
    MY_DATABASE_HOST='127.0.0.1'  # <--------- must be =