我目前正在为我的服务器开发一个新的discord机器人,我刚刚开始使用.js文件来存储永久数据。我已经设置了一个系统来记录参加突袭的人,输入“完成等...如果我存储数据的.js文件是空的,一切正常,所有数据都被正确地写入文件。但是,如果机器人重新启动,然后.js文件已经包含了其他参与者的数据,并且我试图向该文件写入新数据,它将抛出”意外令牌“错误。
我尝试过使用fs.writeFileSync(),但似乎不能解决这个问题,我做了很多研究,但似乎找不到我的问题的具体答案。
要写入的空文件:
{
}在数据已经存在的情况下创建文件:
{
"2887482348774": {
"amount": 1
},
"1746782476348": {
"amount": 1
}
}假的不和谐身份证。
命令代码:
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)发布于 2019-10-12 05:05:37
问题是您正在使用require()读入一个扩展名为.js的json文件。这是意想不到的。如果您将文件更改为具有.json扩展名,则会解决此问题。
您可能希望使用fs模块读取文件,而不是使用require(),因为它将提供更大的灵活性,并且可能是更好的实践。
https://stackoverflow.com/questions/58348024
复制相似问题