繁体   English   中英

Node.js 的 JSON 中的多个配置

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM