[英]Multiple Config in JSON for Node.js
我不知道給我的問題取什么標題。 node.js 是一次冒險,一位樂於助人的人向我指出了 ioredis。 目前我有:
var Redis = require("ioredis");
const DBConfig = require(__dirname+'/../Config.json');
var cluster = new Redis.Cluster([
{
port: 6001,
host: "10.0.0.6",
},
{
port: 6002,
host: "10.0.0.5",
},
{
port: 6003,
host: "10.0.0.4",
},
{
port: 6004,
host: "10.0.0.3",
},
{
port: 6005,
host: "10.0.0.2",
},
{
port: 6006,
host: "10.0.0.1",
},
]);
但對我來說,這似乎在 json 配置文件中會更好......
配置 json:
{
"configA" : "abc",
"someotherconfigB" : "Stuff",
"foo" : "bar"
}
{
"port": 6001,
"host": "10.0.0.6",
},
{
"port": 6002,
"host": "10.0.0.5",
},
{
"port": 6003,
"host": "10.0.0.4",
},
{
"port": 6004,
"host": "10.0.0.3",
},
{
"port": 6005,
"host": "10.0.0.2",
},
{
"port": 6006,
"host": "10.0.0.1",
},
}
我很新,我只是不確定如何在沒有語法錯誤的情況下實現它。
var Redis = require("ioredis");
const DBConfig = require(__dirname+'/../Config.json');
var cluster = new Redis.Cluster([DBConfig.redis]);
我不確定如何實現“var cluster = new Redis.Cluster([DBConfig.redis]);” 適當地
您應該將這些設置聲明為一個鍵下的數組
{
"configA" : "abc",
"someotherconfigB" : "Stuff",
"foo" : "bar",
"redisCluster": [
{
"port": 6001,
"host": "10.0.0.6"
},
{
"port": 6002,
"host": "10.0.0.5"
},
{
"port": 6003,
"host": "10.0.0.4"
}
]
}
然后使用該鍵訪問所需配置文件中的該值。
const DBConfig = require('../Config.json');
const cluster = new Redis.Cluster(DBConfig.redisCluster);
首先,您需要有一個適當的配置文件。 您的文件似乎包含一些配置信息和節點信息。 我會建議:
Config.json
文件:
{
"configs": {
"configA": "abc",
"someotherconfigB": "Stuff",
"foo": "bar"
},
"nodes": [
{
"port": 6001,
"host": "10.0.0.6"
},
{
"port": 6002,
"host": "10.0.0.5"
},
{
"port": 6003,
"host": "10.0.0.4"
},
{
"port": 6004,
"host": "10.0.0.3"
},
{
"port": 6005,
"host": "10.0.0.2"
},
{
"port": 6006,
"host": "10.0.0.1"
}
]
}
然后您的文件應如下所示:
const Redis = require('ioredis');
const DBConfig = require(__dirname + '/Config.json');
const cluster = new Redis.Cluster(DBConfig.nodes);
Object.entries(DBConfig.configs).map(([key, value]) => {
cluster.set(key, value);
});
DBConfig.nodes
它已經是一個數組。 無需在其周圍放置括號
Object.entries(DBConfig.configs)
將為您提供DBConfig.configs
屬性的 [key, value] 對數組
資源:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.