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!

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools
