将目录中的文件名添加到对象

Add filenames from Directory to Object

我正在尝试将包含子目录的目录中的文件名添加到对象。

我的文件夹结构如下图所示:

每次我 运行 我的代码时,只有顶级文件夹中的文件名(这里是命令)被添加到我的对象中。

async function getCommands() {
   let commands = {};

   //get all enteties from folder
   let commandFiles = await fs.promises.readdir("./commands/", (err, elements) => {
       if (err) return console.log(err);
   });

   commandFiles.forEach(file => { //loop through all elements in folder "commands"
      const element_in_folder = fs.statSync(`./commands/${file}`)
      if (element_in_folder.isDirectory() == true) { //check if element in folder is a subfolder
         const sub_directory = `./commands/${file}/`;
         addCommandsFromSubFolder(commands, sub_directory);
      } else {
         //add command to object
         commands[Object.keys(commands).length] = {
            "command": file
         }
      }
   });
   return commands; //return full object with all commands
}

function addCommandsFromSubFolder(commands, sub_directory) {
   //loop through all files in subfolders
   fs.readdir(sub_directory, (err, files) => {
      if (err) return console.log(err);
      let commandsInSubFolder = files.values();
      //add files from subfolder to the object
      for (const command of commandsInSubFolder ) {
         commands[Object.keys(commands).length] = {
            "command": command
         }
      }
   });
}

如果我在 addCommandsFromSubFolder 中记录 commands,我仍然可以看到,所有子文件夹中的文件仍然被添加,但节点不会等待它们被添加。

您应该等待子文件夹的函数调用

async function getCommands() {
   let commands = {};

   //get all enteties from folder
   let commandFiles = await fs.promises.readdir("./commands/", (err, elements) => {
       if (err) return console.log(err);
   });

   for (const file of commandFiles) {
      const element_in_folder = fs.statSync(`./commands/${file}`)
      if (element_in_folder.isDirectory() == true) { //check if element in folder is a subfolder
         const sub_directory = `./commands/${file}/`;
         await addCommandsFromSubFolder(commands, sub_directory);
      } else {
         //add command to object
         commands[Object.keys(commands).length] = {
            "command": file
         }
      }
   }

   return commands; //return full object with all commands
}

async function addCommandsFromSubFolder(commands, sub_directory) {
    try {
        files = await fs.promises.readdir(sub_directory);
        for (const command of commandsInSubFolder ) {
            commands[Object.keys(commands).length] = {
                "command": command
            }
        }
    } catch (e) {
        console.log('e', e);
    }
}

只有你应该注意像这样要求fs(只有节点> 10):

const { promises: fs } = require("fs");

对于 node < 10 你应该使用 promise 来等待