繁体   English   中英

将目录中的文件名添加到 Object

[英]Add filenames from Directory to Object

我正在尝试将具有子目录的目录中的文件名添加到 object。

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

在此处输入图像描述

每次我运行我的代码时,只有顶层文件夹中的文件名(这里是命令)被添加到我的 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 ,我仍然可以看到,所有子文件夹中的文件仍然被添加,但节点不会等待它们被添加。

您应该等待 function 调用子文件夹

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");

对于节点 < 10,您应该使用 promise 等待

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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