嗨,我目前正在使用 discord.js 托管一個不和諧的機器人。我嘗試使用 .json 檔案保存用戶資料。不知何故,我得到了很多錯誤。(我在heroku上托管它)。我不是以英語為母語的人,對這樣的警告一無所知。這是什么意思?我怎么知道哪條線路受到影響?
錯誤:
node:internal/fs/utils:671
throw new ERR_INVALID_ARG_TYPE(propName, ['string', 'Buffer', 'URL'], path);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received an instance of Object
at Object.openSync (node:fs:583:10)
at Object.readFileSync (node:fs:459:35)
at Object.<anonymous> (C:\Users\User\Documents\GitHub\Squidbot1\index.js:9:20)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Module._load (node:internal/modules/cjs/loader:827:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47 {
code: 'ERR_INVALID_ARG_TYPE'
}
Node.js v18.3.0
機器人代碼:
const express = require("express");
const app = express();
const discord = require("discord.js");
const client = new discord.Client({intents:["GUILDS","GUILD_MESSAGES"]});
const fs = require("fs");
var data = require("./userdata.json");
var read_data = fs.readFileSync(data);
var datafile = JSON.parse(read_data);
var bump_timeout = true;
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
client.on("message", message => {
var msg_value = message.content.toLowerCase();
var username = message.author.username;
var id = message.author.id;
if(msg_value.includes('hello') && msg_value.includes('bot') || msg_value.includes('hi') && msg_value.includes('bot')){
message.channel.send("hi dad");
}
if(message.content === "!d bump" && bump_timeout==true){
if(!datafile[id]){
datafile[id] = {coins: 100};
fs.writeFileSync(data, JSON.stringify(read_data, null, 2));
message.channel.send(`<@${id}> got 100 coins!`);
}
else{
var chillcoins = Number(datafile.coins) 100;
datafile[id] = {coins: chillcoins};
fs.writeFileSync(data, JSON.stringify(datafile, null, 2));
message.channel.send(`<@${id}> got ${chillcoins} coins!`);
};
bump_timeout = false;
setTimeout(bump_switchtimeout, 5000);
}
})
function bump_switchtimeout(){
bump_timeout = true;
}
client.on("ready", () => {
console.log("bot is ready");
})
client.login(process.env.token);
有人可以向我解釋錯誤嗎?謝謝
uj5u.com熱心網友回復:
您傳遞的是檔案而不是路徑字串。嘗試將其更改為:
var read_data = fs.readFileSync("./userdata.json");
uj5u.com熱心網友回復:
問題在這里:
var data = require("./userdata.json");
var read_data = fs.readFileSync(data);
var datafile = JSON.parse(read_data);
注意如何data回傳一個物件。您可能只想簡單地讀取檔案并決議 JSON:
// no `data` declaration
var read_data = fs.readFileSync("./userdata.json");
var datafile = JSON.parse(read_data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/491772.html
