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

前端 未结 30 1142

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 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}`);
    
        });
    });
    

提交回复
热议问题