javascript - 为什么我的代码在写入文件时收到未定义?
问题描述
我正在尝试将所有消息记录在我服务器上机器人的文件中。但是,每当我运行我的机器人并且有人发送消息时,我都会收到此错误:
UnhandledPromiseRejectionWarning:TypeError [ERR_INVALID_CALLBACK]:回调必须是函数。收到未定义
这是我的代码:
if (message.channel.type !== 'dm')
{
var log = `[SERVER MESSAGE] ${message.member.user.tag}: "${message.content}" in #${message.channel.name}`;
console.log(log);
fs.writeFile("C:/Users/dubwi/Desktop/Discord_Bot/chatlog.json", `${log}`)
}
else{
message.reply("I don't accept DMs at the moment");
var log = `[DM MESSAGE] ${message.author.tag}: "${message.content}"`;
console.log(log);
fs.writeFile("C:/Users/dubwi/Desktop/Discord_Bot/chatlog.json", `${log}`)
}
解决方案
您正在使用异步方法(fs.writeFile - doc),它需要一个回调函数。
因此,您可以使用不需要回调的同步方法 (fs.writeFileSync - doc ),也可以修改代码以使用回调
希望这可以帮助