【问题标题】:can't seem to append to a .json array似乎无法附加到 .json 数组
【发布时间】:2020-03-26 22:09:23
【问题描述】:

目前我正在尝试为我的不和谐机器人添加黑名单数组。读取数组工作正常,但每当我尝试附加到机器人节点时,都会以代码 1 退出。

我尝试了几种方法,但似乎都没有真正奏效。

const data = require('./data.json');
data.serverData.blackListedColors.append(randomRoleColor);

返回:

                        data.serverData.blackListedColors.append(randomRoleColor);
                                                          ^

TypeError: data.serverData.blackListedColors.append is not a function
    at Client.<anonymous> (C:\Users\mtutt\OneDrive\Documenten\DiscordKeyBot\bot.js:363:59)
    at Client.emit (events.js:209:13)
    at MessageCreateHandler.handle (C:\Users\mtutt\OneDrive\Documenten\DiscordKeyBot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (C:\Users\mtutt\OneDrive\Documenten\DiscordKeyBot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
    at WebSocketConnection.onPacket (C:\Users\mtutt\OneDrive\Documenten\DiscordKeyBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (C:\Users\mtutt\OneDrive\Documenten\DiscordKeyBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (C:\Users\mtutt\OneDrive\Documenten\DiscordKeyBot\node_modules\discord.js\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:209:13)
    at Receiver.receiverOnMessage (C:\Users\mtutt\OneDrive\Documenten\DiscordKeyBot\node_modules\discord.js\node_modules\ws\lib\websocket.js:789:20)
    at Receiver.emit (events.js:209:13)

Process finished with exit code 1

我尝试过使用.parse.add,但它们似乎也不起作用。

使用.push 似乎不会使其崩溃,但也不会将字符串添加到.json 文件中。

编辑: 这是.json 文件供参考

{
  "serverData": {
    "muffinID": "[disocrdID]",
    "token": "[token]",
    "blackListedColors": []
}

【问题讨论】:

  • data.serverData.blackListedColors 显然不是数组
  • 你能把JSON文件的结构贴出来吗,如果data.serverData.blackListedColors是一个数组,那么你可以使用Array.concat,否则你可能需要添加一个新的propoerty并设置它的值(例如data.serverData.blackListedColors["&lt;newproperty&gt;"] = randomRoleColor
  • @AkashShrivastava concat 函数也不会将其写入文件中。

标签: javascript node.js json bots discord


【解决方案1】:

由于节点需要缓存,您不能将 require() 用于在机器人进程的生命周期内发生更改的数据。此外,仅修改data 不会自动将其持久化回文件中;您必须将其写回文件中。

写自己不是火箭手术,但你可能想研究一个为你做这件事的库——我还没有尝试过,但它看起来很有希望:https://www.npmjs.com/package/json-persistent-object

【讨论】:

  • 我尝试像这样导入它:` import data from "./data.json" `
  • 这和requirein基本一样。你必须使用fs.readFile/fs.writeFile
  • 我尝试了你推荐的 json 持久对象,它在数组上使用 .push 效果很好
  • 我什至不需要更改代码就可以工作,非常感谢!
猜你喜欢
  • 2019-09-08
  • 1970-01-01
  • 2020-11-18
  • 2021-12-31
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
相关资源
最近更新 更多