我有這段代碼,它回圈遍歷檔案夾中的所有目錄commands,然后回圈遍歷每個目錄中的每個檔案。然后匯入模塊,將其轉換為 JSON 并將其添加到名為 的陣列commands和名為的映射中client.commands。
let commands = [];
client.commands = new Map();
fs.readdir(__dirname "/../commands/", (err, dirs) => {
if (err) return console.error(err);
for (let dir of dirs) {
fs.readdir(__dirname `/../commands/${dir}/`, (err, files) => {
if (err) return console.error(err);
for (let file of files) {
let command = require(`../commands/${dir}/${file}`);
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
console.log(commands);
}
});
}
});
console.log(commands);
如果我console.log是commands最里面的 for 回圈中的值,則輸出完全符合預期。但是,如果我將它記錄在整個代碼塊的外部,它只會列印一個空串列。
uj5u.com熱心網友回復:
我認為您應該使用遞回來遞回讀取檔案夾中的檔案。下面鏈接已經提出的問題,我認為這將有助于解決這個問題。 Node.js fs.readdir 遞回目錄搜索
uj5u.com熱心網友回復:
這對我來說看起來像 discord.js。
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`.commands/${file}`);
client.commands.set(command.name, command);
}
你的命令應該是這樣的
module.exports = {
name: "name",
description: "description",
execute() {
// execution code
}
}
然后您可以通過呼叫函式或獲取變數來使用它
client.commands.get(/* Name of command */).execute();
uj5u.com熱心網友回復:
由于 readdir() 是異步的,因此在完全執行中間的函式之前呼叫外部 console.log() 。
我將語法調整為更現代的 async 和 await,因為回退函式不再是最佳實踐,不幸的是我無法測驗它,但它至少是正確的方法;)
let commands = [];
client.commands = new Map();
async function main() {
try {
const dirs = await fs.readdir(__dirname "/../commands/")
for (let dir of dirs) {
const files = await fs.readdir(__dirname `/../commands/${dir}/`)
for (let file of files) {
let command = require(`../commands/${dir}/${file}`);
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
console.log(commands);
}
}
} catch (error) {
console.error(err)
}
console.log(commands);
}
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/378987.html
標籤:javascript 节点.js 数组
上一篇:從提供程式(不同的腳本)的異步/同步函式的混合回傳一個值以表達服務器
下一篇:反應onClick不觸發組件
