我目前有一個 Discord.JS 命令處理程式,用于加載命令檔案夾中的所有命令。但是,由于所有命令,它現在變得有點混亂,因此我一直在嘗試實作子檔案夾。這將清理命令檔案夾內的檔案,將它們組織成檔案夾組。
我目前有此代碼用于在同一檔案夾中加載命令。
但是我被困在如何進入命令目錄中的每個檔案夾并加載命令。如果有人可以幫助我,那將不勝感激。
const allCommands = fs.readdirSync('./commands');
for (const command of allCommands) {
try {
const loadedCommand = require(`./commands/${command}`);
commands.set(loadedCommand.name, loadedCommand);
for(const alias of loadedCommand.aliases || [])
commands.set(alias, { ...loadedCommand, alias: true });
logger.info(`Loaded command ${loadedCommand.name} (${command})`);
} catch (error) {
logger.error(`Failed to load command ${command}. **Please report the following error:**`);
logger.error(error);
}
}
uj5u.com熱心網友回復:
老實說,我不建議以這種方式匯入。如果您將每個命令匯入到一個單獨的 javascript 檔案中,然后從那里匯出您的每個命令,那么您的運氣可能會更好,它應該使您的控制器級代碼更易于閱讀
uj5u.com熱心網友回復:
將所有內容移動到其自己的函式中,并將路徑作為引數。每次找到檔案夾時,呼叫帶有檔案夾路徑的函式。
(function readdir(path='./commands') {
const allCommands = fs.readdirSync(path);
for (const command of allCommands) {
if(fs.statSync(`${path}/${command}`).isDirectory()) {
readdir(`${path}/${command}`);
continue;
}
try {
const loadedCommand = require(`${path}/${command}`);
commands.set(loadedCommand.name, loadedCommand);
for(const alias of loadedCommand.aliases || [])
commands.set(alias, { ...loadedCommand, alias: true });
logger.info(`Loaded command ${loadedCommand.name} (${path}/${command})`);
} catch (error) {
logger.error(`Failed to load command ${path}/${command}. **Please report the following error:**`);
logger.error(error);
}
}
})();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/339328.html
標籤:javascript 不和谐 不和谐.js FS
