简体   繁体   中英

nestJs handle env variables

I would configure enivrement variables in nestjs as mentioned in documentation here :

in my service constructor I get env file path

import * as dotenv from 'dotenv';
import * as fs from 'fs';

export class ConfigService {
  private readonly envConfig: { [key: string]: string };

  constructor(filePath: string) {
    this.envConfig = dotenv.parse(fs.readFileSync(filePath))
    console.log(this.envConfig)
  }

  get(key: string): string {
    return this.envConfig[key];
  }
}

Then in config module I set the config service

  providers: [
    {
      provide: ConfigService,
      useValue: new ConfigService(`${process.env.NODE_ENV}.env`),
    },
  ],
  exports: [ConfigService],
})

Current behavior

Actually I get process.env.NODE_ENV value undefined

Expected behavior

get env variable path in process.env.NODE_ENV

I've faced the same issue. Easy fixed it by manually importing dotenv in file main.ts , just like in the example below (please make sure you've installed dotenv ):

import { NestFactory } from '@nestjs/core';
import { config } from 'dotenv';
config();
// all rest of your code

Hope it might help!

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