0
0

More than 1 year has passed since last update.

Nodejsでフォルダ内のファイルから繰り返し処理でmoduleを読み込む

Posted at

こんにちはAmpoiです。Skuronosukeから名前を変えて初めての投稿となりますが、この記事ではDiscordJSでコマンドの情報と各コマンドの実行内容を繰り返し処理で取得したい時などに使えるNodejsでフォルダ内のファイルから繰り返し処理でmoduleを読み込む方法を紹介していきます。

やりかたー

fsモジュールを使ってフォルダ内のファイルを繰り返し処理で取得し、それらのファイルの中にあるデータをfsコマンドで取得・リストに格納します。

コード

//./commands/hogehoge.js


//commandsフォルダ内にあるファイルの一例
module.exports = function(){
  return {
    data:{
      name: "bot",
      description: "どういうことBOT「どういうこと」",
      options: [
        {
          type: 3,
          name: "moji",
          required: true,
          description: "BOT風にする文字を入力"
        }
      ]
    },
    command(interaction){
      const moji = interaction.options.getString("moji")
      interaction.reply(`${moji}bot「${moji}」`)
    }
  }
}
//index.js

//コマンドデータ
const fs = require("fs") //fsモジュールのインストール
const path = require("path") //pathモジュールのインストール
const command_folder = "./commands/" //読み込むファイルたちが入ってる親フォルダ
let commands = [] //読み込んだコマンドの情報を格納するフォルダ(interaction)
let command_functions = {} //コマンドの関数を格納するフォルダ
//command_folder内の.jsファイルを取得
const files = fs.readdirSync(command_folder)
  .filter((file) => {
      return path.extname(file).toLowerCase() === ".js"; 
  })
files.forEach((file) => {
  const command_file_setup = require(`${command_folder}${file}`) //ファイルの場所
  //以下DiscordJS関係
  const command_file = command_file_setup()
  commands.push(command_file.data)
  command_functions[command_file.data.name] = command_file.command
})
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0