简体   繁体   中英

Get .env variable inside object in the controller NestJS

I created .env

APP_PORT=3001
DEST=C:\data\formations

I have configService:ConfigService in the controller contractor. I want to get DEST for destination from .env in this code.

@UseInterceptors(FileInterceptor('file', {
  storage: diskStorage({
    destination: /*here*/ ,
    filename: (req, file, cb) => {
      const filename: string = path.parse(file.originalname).name.replace(/\s/g, '')
      const extension: string = path.parse(file.originalname).ext
      cb(null, `${filename}${extension}`)
    }
  })
}))

When I use this inside this other object I get an error.

You should use the ConfigModule for getting the environment varible.

Check the document: https://docs.nestjs.com/techniques/configuration

If you want to use configuration outside Nest's IoC container, you can try nest-typed-config :

import { selectConfig } from 'nest-typed-config';
import { ConfigModule, FileConfig } from '@/module/config';

const fileConfig = selectConfig(ConfigModule, FileConfig);

@UseInterceptors(FileInterceptor('file', {
  storage: diskStorage({
    destination: fileConfig.destination,
    filename: (req, file, cb) => {
      const filename: string = path.parse(file.originalname).name.replace(/\s/g, '')
      const extension: string = path.parse(file.originalname).ext
      cb(null, `${filename}${extension}`)
    }
  })
}))

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