简体   繁体   中英

How to iterate through a folder in JavaScript?

I am trying to iterate through a folder of command files to make a help command for a discord bot. This is my code so far.

module.exports = {
  name: 'help',
  description: 'Lists current commands.',
  execute(message) {
    //was the first time i made something interesting out of a for loop
    if (message.content.toLowerCase() === '$help') {
      const commands = 'C:/Bot/commands';
      const Discord = require('discord.js');
      const helpEmbed = new Discord.MessageEmbed()
        .setTitle("Commands")
        .setColor(0x6e7175)
        .setFooter('Provided by Echo', 'https://cdn.discordapp.com/avatars/748282903997186178/6288e1f487e111b211aa9966c583d948.png?size=128')
        .setTimestamp()

      for (i of commands) {
        let title = i.name
        let value = i.description
        helpEmbed.addField(title, value)
      }
      message.channel.send(helpEmbed)
    }
  }
}

C:/Bot/commands is the folder in which all the commands are stored, at the moment i.name and i.description are undefined. What's the issue here?

C:/Bot/commands is the folder with stored comands, but string 'C:/Bot/commands' is not a folder - it is a string.

For iterate through folder you need to read it by fs.readdir or sync version

commands is currently just a string. If you want to get an array of all files in a folder, use fs .

const fs = require('fs'); // node.js built in module
const files = fs.readdierSync('../commands'); // get the names of all files in the foler

for (file of files) {
 // now you can require the file
 const { name, description } = require(`../commands/${file}`);
 embed.addField(name, description);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM