【发布时间】:2021-02-05 22:44:25
【问题描述】:
我已经在我的 src 文件夹之外的 config 文件夹中创建了我的 .env 文件,我正在尝试将它加载到我的 main.ts 文件中。它总是给我 undefined 或 NAN。
我哪里错了?
【问题讨论】:
标签: javascript node.js express nestjs
我已经在我的 src 文件夹之外的 config 文件夹中创建了我的 .env 文件,我正在尝试将它加载到我的 main.ts 文件中。它总是给我 undefined 或 NAN。
我哪里错了?
【问题讨论】:
标签: javascript node.js express nestjs
安装 dotenv npm i dotenv 并更新 main.ts 文件:
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as dotenv from 'dotenv';
import * as path from 'path';
async function bootstrap() {
dotenv.config({ path: path.resolve(__dirname, '../config/dev.env') });
const app = await NestFactory.create(AppModule);
console.log(process.env.PORT);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
【讨论】:
看起来您从未将 .env 文件加载到您的 process.env 中,dotenv 包使用 config() 方法执行此操作,但您需要提供它的路径,因为您不需要'根目录中没有.env,或命名为.env。您正在使用的 config 包似乎不支持 .env 文件格式,因此您应该使用类似 .json 或 anything else supported by config 的东西
【讨论】:
我已经删除了 src 文件夹之外的 env 文件并创建了配置模块和服务。
ConfigService.ts
import { Injectable } from '@nestjs/common';
import * as path from 'path';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
@Injectable()
export class ConfigService {
static constants(){
const baseDir = path.join(__dirname, '../../dev.env');
const config = dotenv.parse(fs.readFileSync(baseDir));
return {
port: config.PORT,
mongoConnectionString: config.MONGODB_CONNECT,
jwtSecret: config.SECRETKEY,
sessionTime: config.SESSIONTIME
}
}
}
ConfigModule.ts
import { Global, Module } from '@nestjs/common';
import { ConfigService } from './config.service';
@Global()
@Module({
providers: [ConfigService],
exports: [ConfigService]
})
export class ConfigModule {
}
为了使用下面的代码使用值
ConfigService.constants().port
存储库中提供的详细代码
【讨论】: