当前位置:网站首页>Use of dotenv in nestjs
Use of dotenv in nestjs
2022-06-23 22:06:00 【Swing a knife North】
Dotenv Is a zero dependency module , It can change the variables in the environment variables from .env File loading to process.env in .
Use Install... In the project dotenv
npm install dotenv -S
Created in the root directory .env file
HOST=localhost PORT=3000 MONGOOSE_URL=mongodb://localhost:27017/test
The root directory app.js Lower introduction dotenv And use
require('dotenv').config({ path: '.env' })
// Use
console.log(process.env.HOST) // localhost
console.log(process.env.PORT) // 3000
console.log(process.env.MONGOOSE_URL) // mongodb://localhost:27017/testHow to be in nestjs Use in dotenv Well ?
stay nestjs Using environment variables in , It is recommended to use the official @nestjs/config, Open the box :
@nestjs/config Depend on dotenv, Can pass key=value Configure environment variables as , The project will load... In the root directory by default .env file , We just need to app.module.ts Introduction in ConfigModule, Use ConfigModule.forRoot() The method can , then ConfigService Read the relevant configuration variables .
- First install the corresponding npm package
- Configure environment variable files
- Define functions that read environment variables
- To configure @nestjs/config Methods
First installation @nestjs/config
Configure environment variable files , Configure two files , A development environment , One for the production environment .en file ,.en.prod file
// Database address DB_HOST=localhost // Database port DB_PORT=3306 // Database login name DB_USER=root // Database login password DB_PASSWD=root // Database name DB_DATABASE=blog
.env.prod In is the database information to be used on the line , If your project is to be uploaded to online management , For security reasons , It is recommended that this file be added to .gitignore in . Then create a folder under the root directory config( And src At the same level ), Then create another env.ts It is used to read the corresponding configuration files according to different environments .
This file is used to determine whether the current environment is a development environment or a test environment :
import * as fs from 'fs';
import * as path from 'path';
const isProd = process.env.NODE_ENV === 'production';
function parseEnv() {
const localEnv = path.resolve('.env');
const prodEnv = path.resolve('.env.prod');
if (!fs.existsSync(localEnv) && !fs.existsSync(prodEnv)) {
throw new Error(' Missing Environment Profile ');
}
const filePath = isProd && fs.existsSync(prodEnv) ? prodEnv : localEnv;
return { path:filePath };
}
export default parseEnv();The file execution above returns an object :
{path:' Environment variables file '}Then configure @nestjs/config Methods
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigService, ConfigModule } from '@nestjs/config';
import envConfig from '../config/env';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true, // Set to global
envFilePath: [envConfig.path]
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
type: 'mysql', // Database type
entities: [], // Data table entities
host: configService.get('DB_HOST', 'localhost'), // host , The default is localhost
port: configService.get<number>('DB_PORT', 3306), // Port number
username: configService.get('DB_USER', 'root'), // user name
password: configService.get('DB_PASSWORD', 'root'), // password
database: configService.get('DB_DATABASE', 'blog'), // Database name
timezone: '+08:00', // The time zone configured on the server
synchronize: true, // Automatically create database tables based on entities , It is recommended to shut down the production environment
}),
}),
PostsModule,
],
...
})
export class AppModule {}
ConfigModule Of forRoot The function parameter is an object , The more important attribute is isGlobal and envFilePath, This envFilePath It is the environment variable configuration file read according to the environment variables .
How to read process.env Well ? Call directly configService Of get Method ,get The first parameter of the method is the environment variable attribute , The second parameter is the default value .
This is where nestjs Use in dotenv Methods , I hope it helped you .
边栏推荐
- EDI mandatory manual
- Troubleshooting the problem that the channel cannot play after easycvr cascades to the upper platform
- [js] generate random array
- Outlook開機自啟+關閉時最小化
- 【Proteus仿真】LCD1602+DS1307按键设置简易时钟
- To develop AI face comparison, how to output multiple faces with comparative similarity?
- Completely open source and permanently free, this markdown editor is really fragrant!
- How to calculate individual income tax? You know what?
- University of North China, Berkeley University of California, etc. | Domain Adaptive Text Classification with structural Knowledge from unlabeled data
- Acl2022 | MVR: multi view document representation for open domain retrieval
猜你喜欢

Introduction to scikit learn machine learning practice

How to calculate individual income tax? You know what?

Bluetooth chip | Renesas and Ti launch new Bluetooth chip, try Lenz st17h65 Bluetooth ble5.2 chip

HDLBits-&gt; Circuits-&gt; Arithmetic Circuitd-&gt; 3-bit binary adder

Peking University, University of California Berkeley and others jointly | domain adaptive text classification with structured knowledge from unlabeled data (Domain Adaptive Text Classification Based o

Configuring error sets using MySQL for Ubuntu 20.04.4 LTS

Installation and use of Minio

Selenium batch query athletes' technical grades

Selenium批量查询运动员技术等级

Icml2022 | robust task representation for off-line meta reinforcement learning based on contrastive learning
随机推荐
The "Star" industry in the small town is escorted by wechat cloud hosting
[log service CLS] one click to start the efficient operation and maintenance journey of Tencent E-Sign
Embedded development: embedded foundation -- the difference between restart and reset
How to build an API gateway and how to maintain an API gateway?
How to use zero to build a computer room
嵌入式开发:嵌入式基础——重启和重置的区别
Dart series: look at me for security. The security feature in dart is null safety
Improve efficiency, take you to batch generate 100 ID photos with QR code
Surprise! Edge computing will replace cloud computing??
《阿里云天池大赛赛题解析》——O2O优惠卷预测
Start /affinity specifies the number of vcpu to run OpenSSL speed to test the performance of a single vcpu
Icml2022 | robust task representation for off-line meta reinforcement learning based on contrastive learning
Analysis of a series a e-commerce app docommandnative
Bcdedit, used to adjust the machine startup parameters (safe mode, BootMenu display name, CPU, memory, etc.)
Open source C # WPF control library --newbeecoder UI User Guide (II)
How to dynamically insert a picture into a QR code
High quality "climbing hand" of course, you have to climb a "high quality" wallpaper
How to open a stock account? What are the main considerations for opening an account? Is there a security risk in opening an account online?
Digital transformation solution for supply chain platform of mechanical equipment industry
Experiment 5 module, package and Library