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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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