How do I setup the dotenv file in Node.js?

前端 未结 30 1141

I am trying to use the dotenv NPM package and it is not working for me. I have a file config/config.js with the following content:



        
相关标签:
30条回答
  • 2020-12-07 14:59

    Make sure to set cwd in the pm2 config to the correct directory for any calls to dotenv.config().

    Example: Your index.js file is in /app/src, your .env file is in /app. Your index.js file has this

    dotenv.config({path: "../.env"});

    Your pm2 json config should have this: "cwd": "/app/src", "script": "index.js"

    You could also use dotenv.config({path: path.join(__dirname, "../.env")}); to avoid the CWD issue. You will still have a problem if you move the .env or the index.js file relative to each other.

    0 讨论(0)
  • 2020-12-07 15:00

    In my case, I've created a wrapper JS file in which I have the logic to select the correct variables according to my environment, dynamically.

    I have these two functions, one it's a wrapper of a simple dotenv functionality, and the other discriminate between environments and set the result to the process.env object.

    setEnvVariablesByEnvironment : ()=>{
    		return new Promise((resolve)=>{
    
    			if (process.env.NODE_ENV === undefined || process.env.NODE_ENV ==='development'){
    				logger.info('Lower / Development environment was detected');
    
    				environmentManager.getEnvironmentFromEnvFile()
    					.then(envFile => {
    						resolve(envFile);
    					});
    
    			}else{
    				logger.warn('Production or Stage environment was detected.');
    				resolve({
    					payload: process.env,
    					flag: true,
    					status: 0,
    					log: 'Returned environment variables placed in .env file.'
    				});
    			}
    
    
    		});
    	} ,
    
    	/*
    	Get environment variables from .env file, using dotEnv npm module.
    	 */
    	getEnvironmentFromEnvFile: () => {
    		return new Promise((resolve)=>{
    			logger.info('Trying to get configuration of environment variables from .env file');
    
    			env.config({
    				debug: (process.env.NODE_ENV === undefined || process.env.NODE_ENV === 'development')
    			});
    
    			resolve({
    				payload: process.env,
    				flag: true,
    				status: 0,
    				log: 'Returned environment variables placed in .env file.'
    			});
    		});
    	},

    So, in my server.js file i only added the reference:

    const envManager = require('./lib/application/config/environment/environment-manager');
    

    And in my entry-point (server.js), it's just simple as use it.

    envManager.setEnvVariablesByEnvironment()
    .then(envVariables=>{
        process.env= envVariables.payload;
    
        const port = process.env.PORT_EXPOSE;
        microService.listen(port, '0.0.0.0' , () =>{
    
            let welcomeMessage = `Micro Service started at ${Date.now()}`;
            logger.info(welcomeMessage);
    
            logger.info(`${configuration.about.name} port configured  -> : ${port}`);
            logger.info(`App Author: ${configuration.about.owner}`);
            logger.info(`App Version: ${configuration.about.version}`);
            logger.info(`Created by: ${configuration.about.author}`);
    
        });
    });
    
    0 讨论(0)
  • 2020-12-07 15:01

    I am using NodeJS on windows 10. I used process.env.var-name to access the variables but failed because it gives me windows path variables as a JSON object, so I installed dotenv ( npm install dotenv ). dotenv gets process envirnoment variables from your project's .evn file

    1. npm install dotenv or yarn add dotenv

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

    1. process.env.variable_name

    1. output

    0 讨论(0)
  • 2020-12-07 15:01

    Had the same problem. I used dotenv-webpack and need to define

    plugins: [
      new Dotenv()
    ]
    

    in both webpack production and webpack base files (I use webpack merge). If was not defined in both files then it did not work.

    0 讨论(0)
  • 2020-12-07 15:03

    I had a problem also with .env variables not loading and being undefined.

    What I tried:

    index.js:

    import dotenv from 'dotenv';
    dotenv.config();
    import models from './models';
    

    models.js

    import Sequelize from 'sequelize';
    const sequelize = new Sequelize(
        process.env.DATABASE,
        process.env.DATABASE_USER,
        process.env.DATABASE_PASSWORD,
        {
            dialect: 'postgres',
        }
    );
    

    Apparently, because of how loading the imports works in nodejs, the import of models in index.js caused that the models.js was executed before dotenv.config(). Therefore I got undefined values from process.env.

    When I changed models.js to do the dotenv configuration like:

    import Sequelize from 'sequelize';
    import dotenv from 'dotenv';
    dotenv.config();
    const sequelize = new Sequelize(
        process.env.DATABASE,
        process.env.DATABASE_USER,
        process.env.DATABASE_PASSWORD,
        {
            dialect: 'postgres',
        }
    );
    

    it started to work!

    0 讨论(0)
  • 2020-12-07 15:03

    I cloned a repo from Github and went through every one of the suggestions here. After a lot of frustration, I realized that npm install did not install any of the modules and my node_modules folder was empty the whole time.

    QUICK FIX:
    1) delete your node_modules folder
    2) delete your package-lock.json
    3) run npm install

    0 讨论(0)
提交回复
热议问题