@webantic/nginx-config-parser nodejs nginx conf 解析以及生成處理包試用
阿新 • • 發佈:2022-04-09
@webantic/nginx-config-parser 是一個基於nodejs 開發nginx 配置解析工具
參考使用
- demo.conf
upstream mydemoapp {
# simple round-robin
server app1:80;
server app2:80;
check interval=1000 rise=2 fall=5 timeout=1000 type=http;
check_http_send "HEAD / HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
server {
listen 80;
server_name mydemoapp.com;
location / {
root html;
index index.html index.htm;
proxy_pass http://mydemoapp;
}
location /status {
healthcheck_status;
}
}
server {
listen 443 http2;
server_name mydemoapp.com;
ssl app/cer;
location / {
root html;
index index.html index.htm;
proxy_pass http://mydemoapp;
}
location /status {
healthcheck_status;
}
}
- app.js
var ConfigParser = require('@webantic/nginx-config-parser')
var parser = new ConfigParser()
// parse straight from file. by default, will try to resolve includes
var config = parser.readConfigFile('demo.conf')
// to keep deterministic behaviour, set parseIncludes = false in the options
var configWithoutIncludes = parser.readConfigFile('demo.conf', { parseIncludes: false })
// write direct to file (overwriting existing one)
// 讀取寫到其他地方,比如基於json的解析,然後寫到一個s3 的掛載中
parser.writeConfigFile('mynginx.conf', config, true)
console.log(configWithoutIncludes.server)
// 基於json 的nginx 配置生成
var sampleConfig = {
"upstream mydemoapp":{
"server":[
"app1:80",
"app2:80"
],
"check":"interval=1000 rise=2 fall=5 timeout=1000 type=http",
"check_http_send":"\"HEAD / HTTP/1.0\\\\r\\n\\r\\n\"",
"check_http_expect_alive":"http_2xx http_3xx"
},
"server":[
{
"listen":"80",
"server_name":"mydemoapp.com",
"location /":{
"root":"html",
"index":"index.html index.htm",
"proxy_pass":"http://mydemoapp"
},
"location /status":{
"healthcheck_status":""
}
},
{
"listen":"443 http2",
"server_name":"mydemoapp.com",
"ssl":"app/cer",
"location /":{
"root":"html",
"index":"index.html index.htm",
"proxy_pass":"http://mydemoapp"
},
"location /status":{
"healthcheck_status":""
}
}
]
}
// to multi-line config string
var configString = parser.toConf(sampleConfig)
var configString2 = parser.parse(sampleConfig)
console.log("app:",configString)
console.log("app2:",configString2)
// and back again
var configJson = parser.toJSON(configString)
// shorthand (will change object --> string and string --> object)
parser.parse(configString)
console.log(JSON.stringify(config))
說明
目前關於nginx 解析方便的工具並不是很多(主要是nginx 配置並不是很複雜,我們基於模版引擎也可以解決)
@webantic/nginx-config-parser 是一個不錯的選擇,可以解決我們管理nginx 配置的一些問題,而且支援json 以及nginx 配置的模式
整合到我們的系統中是一個不錯的選擇