Introduction to nodejs configuration file processing methods
This article brings you an introduction to the method of processing nodejs configuration files. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Generally speaking: a good project configuration should meet the following conditions:
Dependent environment: The configuration depends on the specific operating environment. Corresponding file reading
Code separation: Configuration items can not only be read from configuration files, but also from environment variables, making configuration items safe and confidential Separation from code
Easy to use: Configuration items should be hierarchically configured to facilitate finding entries and maintaining huge configuration files, and should be easy to organize And those that are easy to obtain, such as
json
structure
When multiple people develop nodejs projects, if the configuration plan is not planned, problems with the configuration file will be easily exposed. .
Pain Points
In the project of developing nodejs, I encountered three pain points
Different deployment environments: Development, Differences in test and production environments lead to different configurations
Differences in development environments: If the developer's development environment configuration is different, there will be different configuration items for the same configuration file Submitting different contents of the same file can easily cause git conflicts and affect git submission updates
Safe configuration: Some configurations should not be saved in clear text in the project code, such as Database password
Solution
Different deployment environments
For different deployment environments, it is relatively easy to solve. Create a configuration file for the corresponding environment, such as:
Development environment configuration: developmentConfig.js
Test environment configuration: testConfig.js
Production Environment configuration: productionConfig.js
Create another config.js
configuration file as the entrance to obtain the configuration, as follows:
module.exports = require(`./${process.env.NODE_ENV}Config.js`)
When referencing the configuration, Just quote config.js
.
Run the command as follows:
NODE_ENV=development node index.js
Different development environments
For different development environments, everyone’s developmentConfig.js
Different, this cannot require other people’s configuration to be the same as yours, otherwise the project will be too hard.
We can add developmentConfig.js
to .gitignore
to separate it from the project, and then explain how to configure developmentConfig in
readme.md .js
.
It is best to create a developmentConfig.example.js
and copy the document description into developmentConfig.js
and then modify the configuration items to match your own development configuration.
Secure configuration
For some configuration items with high security requirements in the project, we should separate them from the configuration file. They can only be obtained in the current running process. The configuration items in the configuration file are then To read the configuration item values of the process, such as database password, the general method is as follows: productionConfig.js
module.exports = { database: { user: process.env.user || 'root', password: process.env.password || 'yfwzx2019' } }
The more secret method is that you don’t know that I use environment variables. Overwrites the configuration item value, for example:
productionConfig.js
module.exports = { database: { user: 'root', password: 'yfwzx2019' } }
When most people get this configuration, they will think that the database account password is root
, yfwzx2019
, will actually be overwritten by the value of the environment variable in the end. Run as follows:
node index.js --database_user=combine --database_password=tencent2019
Of course, some processing needs to be done before it can be configured like this.
Practical operation
Now that we have the plan, let’s first introduce the following nodejs configuration module rc module
rc module
Userc
The module needs to define a appname
. The rc
module is selected because it will read configurations from as many places as possible related to the appname
naming.
It is also very simple to use. First instance an rc configuration:
var conf = require('rc')(appname, defaultConfigObject)
Then it will start from The following list merges the configurations, and the priorities are merged in order:
Command line parameters: --user=root or assignment in object form --database.user=root
Environment variables: The environment variable prefix is ${appname}_The variable appname_user=root Object form appname_database__user=root
Specified file: node index.js --config file
Default configuration file: Search
from
./ ../ ../../ ../../../and other directories. ${appname}rc
File##$HOME/.${appname}rc
$HOME/.${appname}/config
$HOME/.config/${appname}
$HOME/.config/${appname}/config
- ##/etc/${appname}rc
- /etc/${appname}/config
var conf = require('rc')('development', { port: 3000, }) console.log(JSON.stringify(conf)) // 1、直接运行 // node index.js // { port: 3000, _: [] } // 2、加上命令行参数 // node index.js --port=4000 --database.user=root // { port: 4000, _: [], database: { user: 'root' } } // 3、加上环境变量 // development_port=5000 development_database__password=yfwzx2019 node index.js // {"port":"5000","database":{"password":"yfwzx2019"},"_":[]} // 4、指定配置文件:根目录建一个配置文件 config.json, 内容如下 // { // "port": "6000" // } // node index.js --config=config.json // {"port":"6000","_":[],"config":"config.json","configs":["config.json"]} // 5、默认读取 ${appname}rc 文件:根目录见一个配置文件 .developmentrc 内容如下: // { // "port": 7000 // } // node index.js // {"port":7000,"_":[],"configs":[".developmentrc"],"config":".developmentrc"} // 6、 5 和4 一起运行 // node index.js --config=config.json // {"port":"6000","_":[],"config":"config.json","configs":[".developmentrc","config.json"]}
具体操作
看了 rc 模块,可以满足我们的需求,我们可以配置公共的配置项,也可以隐秘的覆盖我们的配置项。
创建配置文件目录,添加配置文件
├── config │ ├── .developmentrc.example │ ├── .productionrc │ ├── .testrc │ └── index.js
其中 .developmentrc.example 是开发环境的例子,然后开发人员参考建 .developmentrc 文件, index.js 是配置入口文件,内容如下:
let rc = require('rc') // 因为 rc 是从 process.cwd() 向上查找 .appnamerc 文件的,我们在根目录 config 文件夹里面的是找不到的,要改变工作路径到当前,再改回去 var originCwd = process.cwd() process.chdir(__dirname) var conf = rc(process.env.NODE_ENV || 'production', { // 默认的共同配置 origin: 'default', baseUrl: 'http://google.com/api', enableProxy: true, port: 3000, database: { user: 'root', password: 'yfwzx2019' } }) process.chdir(originCwd) module.exports = conf
关于部署环境的不同,获取配置通过设置环境变量
NODE_ENV
来适配关于开发环境的不同,在
.gitignore
添加config/.developmentrc
,项目代码去掉开发环境配置.developmentrc
,开发人员根据.developmentrc.example
建直接的开发配置.developmentrc
关于安全地配置,通过添加环境变量覆盖默认值,可以安全隐秘地覆盖配置项,比如:
NODE_ENV=production node index.js --database.password=tencent2019
The above is the detailed content of Introduction to nodejs configuration file processing methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

How does Node.js do GC (garbage collection)? The following article will take you through it.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".
