【发布时间】:2021-08-13 18:17:19
【问题描述】:
我正在尝试将带有子目录的目录中的文件名添加到对象中。
我的文件夹结构如下图所示:
每次我运行我的代码时,只有顶层文件夹中的文件名(这里是命令)被添加到我的对象中。
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,我仍然可以看到,所有子文件夹中的文件仍然被添加,但节点不会等待它们被添加。
【问题讨论】:
标签: javascript node.js object fs