Home >Web Front-end >JS Tutorial >Introduction to nodejs configuration file processing methods

Introduction to nodejs configuration file processing methods

不言
不言forward
2019-01-02 09:51:034101browse

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:

  1. Dependent environment: The configuration depends on the specific operating environment. Corresponding file reading

  2. 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

  3. 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 jsonstructure

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

  1. Different deployment environments: Development, Differences in test and production environments lead to different configurations

  2. 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

  3. 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:

  1. Development environment configuration: developmentConfig.js

  2. Test environment configuration: testConfig.js

  3. 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.jsDifferent, 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

UsercThe 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:

  1. Command line parameters: --user=root or assignment in object form --database.user=root

  2. Environment variables: The environment variable prefix is ​​${appname}_The variable appname_user=root Object form appname_database__user=root

  3. Specified file: node index.js --config file

  4. Default configuration file: Search from ./ ../ ../../ ../../../ and other directories. ${appname}rcFile

  5. ##$HOME/.${appname}rc

  6. $HOME/.${appname}/config

  7. $HOME/.config/${appname}

  8. $HOME/.config/${appname}/config

  9. ##/etc/${appname}rc

  10. /etc/${appname}/config

  11. I made a demo to make it more intuitive
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 模块,可以满足我们的需求,我们可以配置公共的配置项,也可以隐秘的覆盖我们的配置项。

  1. 创建配置文件目录,添加配置文件

├── 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
  1. 关于部署环境的不同,获取配置通过设置环境变量NODE_ENV来适配

  2. 关于开发环境的不同,在.gitignore添加config/.developmentrc,项目代码去掉开发环境配置.developmentrc,开发人员根据.developmentrc.example建直接的开发配置.developmentrc

  3. 关于安全地配置,通过添加环境变量覆盖默认值,可以安全隐秘地覆盖配置项,比如:

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete