Table of Contents
Pain Points
Solution
Different deployment environments
Different development environments
Secure configuration
Practical operation
rc module
具体操作
Home Web Front-end JS Tutorial Introduction to nodejs configuration file processing methods

Introduction to nodejs configuration file processing methods

Jan 02, 2019 am 09:51 AM
node.js

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`)
Copy after login

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'
    }
}
Copy after login

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'
    }
}
Copy after login

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"]}
Copy after login

具体操作

看了 rc 模块,可以满足我们的需求,我们可以配置公共的配置项,也可以隐秘的覆盖我们的配置项。

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

├── config
│   ├── .developmentrc.example
│   ├── .productionrc
│   ├── .testrc
│   └── index.js
Copy after login

其中 .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
Copy after login
  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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

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!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

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

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

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?

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

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.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

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!

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

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

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

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!

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

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

See all articles