javascript - 如何修复JS写入文件时出现 "Unexpected Token :"错误

标签 javascript node.js discord.js

我目前正在为我的服务器开发一个新的不和谐机器人,并且我刚刚开始使用 .js 文件来存储永久数据。我已经建立了一个系统,通过输入“[已完成]等来记录突袭的参加者...如果我存储数据的 .js 文件为空,则一切正常,并且所有数据都正确写入该文件。但是,如果机器人重新启动,然后 .js 文件已包含其他与会者的数据,并且我尝试将新数据写入该文件,则会抛出“意外 token ”错误。

我尝试使用 fs.writeFileSync() 但这似乎无法解决问题,我做了很多研究,但似乎找不到我的问题的具体答案。

要写入的空文件:

{

}

当数据已经存在时归档:

{
    "2887482348774": {
        "amount": 1
    },
    "1746782476348": {
        "amount": 1
    }
}

伪造的不和谐 ID。

命令代码:

const Discord = require('discord.js');
const fs = require('fs');

module.exports.run = async (bot, message, args) => {
  bot.msgs = require("./raiddata/raidattendance.js");
  if (message.channel.id !== '631620937418145802') return;
  if (!message.member.roles.some(r => ["Raider in Command", "Permissions"].includes(r.name))) return;

  for (let attenders of message.mentions.users.keyArray()) {
    message.channel.send(`Found user: ${attenders}`);
    bot.msgs [attenders] = {
      amount: 1
    }
    console.log("Works");
    fs.writeFileSync ('./commands/raiddata/raidattendance.js', JSON.stringify (bot.msgs, null, 4), err => {
      if (err) throw err;
    });
    message.channel.send(bot.msgs[attenders].amount);
  }
}

module.exports.config = {
  command: "finished]"
}

我希望代码继续从中断处写入文件,但事实并非如此。这是我得到的错误:

8 commands found.
Command announcement.js loading...
Command changelog.js loading...
Command delete.js loading...
Command lock.js loading...
Command lograid.js loading...
Command notice.js loading...
Command raid.js loading...
Command unlock.js loading...
Bot is now running.
(node:6896) UnhandledPromiseRejectionWarning: C:\Users\Removed\Downloads\Removed\Removed\commands\raiddata\raidattendance.js:2
    "1746782476348": {
                   ^

SyntaxError: Unexpected token :
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (internal/modules/cjs/helpers.js:25:18)

最佳答案

问题是您正在使用 require() 读取扩展名为 .js 的 json 文件。这是预料之外的。如果您将文件更改为具有 .json 扩展名,它将解决该问题。

您可能希望使用 fs 模块而不是使用 require() 来读取文件,因为它会提供更大的灵 active 和更好的实践。

关于javascript - 如何修复JS写入文件时出现 "Unexpected Token :"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58348024/

相关文章:

javascript - 用于在 mm :ss format 中显示计时器的 Moment js

node.js - NodeJS + Express - 将 session 中间件应用于某些路由

javascript - 重新创建具有相同权限的 channel

javascript - 如何修复 'Cannot read property ' 的 'null' id'

javascript - 模块 'ui.bootstrap' 不可用-Angularjs

javascript - 在 h3 标签内复制文本时,复制到剪贴板不是功能

javascript - 如何获取跨度标签的值?

node.js - 链接到其他 Jade 文件

mysql - 当我通过 multer 上传图像时,出现图像未定义错误

javascript - Discord.js 如何知道用户是否阻止了机器人