当前位置:网站首页>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 .
边栏推荐
- 数据可视化之:没有西瓜的夏天不叫夏天
- Start /affinity specifies the number of vcpu to run OpenSSL speed to test the performance of a single vcpu
- HDLBits-&gt;Circuits-&gt;Arithmetic Circuitd-&gt;3-bit binary adder
- How does the API gateway intercept requests? How does the security of the API gateway reflect?
- Benchclock: a benchmark for evaluating semantic analysis language models
- Configuring error sets using MySQL for Ubuntu 20.04.4 LTS
- Open source C # WPF control library --newbeecoder UI User Guide (II)
- Performance optimization of database 5- database, table and data migration
- [same origin policy - cross domain issues]
- How to deal with the situation of repeated streaming and chaotic live broadcast in easydss?
猜你喜欢

Embedded development: embedded foundation -- the difference between restart and reset

北大、加州伯克利大學等聯合| Domain-Adaptive Text Classification with Structured Knowledge from Unlabeled Data(基於未標記數據的結構化知識的領域自適應文本分類)

Simple code and design concept of "back to top"

Analysis of Alibaba cloud Tianchi competition -- prediction of o2o coupon
Performance optimization of database 5- database, table and data migration

MySQL de duplication query only keeps one latest record

Sending network request in wechat applet

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

从CVPR 2022看域泛化(Domain Generalization)最新研究进展

Freshman girls' nonsense programming is popular! Those who understand programming are tied with Q after reading
随机推荐
Embedded development: embedded foundation -- the difference between restart and reset
CMU博士论文 | 通过记忆的元强化学习,118页pdf
Performance optimization of database 5- database, table and data migration
Framework not well mastered? Byte technology Daniel refined analysis notes take you to learn systematically
Code implementation of CAD drawing online web measurement tool (measuring distance, area, angle, etc.)
Dart series: smooth as silk, operating files and directories
Make it simple. This wave of global topology is quite acceptable!
Redis encapsulation instance
Troubleshooting the problem that the channel cannot play after easycvr cascades to the upper platform
Take you to understand the working process of the browser
TDD development mode recommendation process
[同源策略 - 跨域问题]
什么是股票线上开户?手机开户安全么?
Open source C # WPF control library -newbeecoder UI usage guide (I)
Cloud native practice of meituan cluster scheduling system
德国弗莱堡大学、希尔德斯海姆大学等联合 | Zero-Shot AutoML with Pretrained Models(基于预训练模型的零样本AutoML)
《scikit-learn机器学习实战》简介
Smart cockpit SOC competition upgraded, and domestic 7Nm chips ushered in an important breakthrough
Find my information | Apple may launch the second generation airtag. Try the Lenz technology find my solution
Don't let your server run naked -- security configuration after purchasing a new server (Basics)