【发布时间】:2021-04-07 21:52:40
【问题描述】:
我想返回文件夹和子文件夹中存在的文件,但需要过滤扩展名以 .html、.htm 或 .aspx 结尾的文件
我有一个代码,它只返回扩展名为 Index.html, Default.htm, Index.aspx 的文件也需要其余文件,但不知道如何返回文件的其余部分以及过滤后的扩展名
async function getAllFile(folderPath) {
let files = await fs.readdir(folderPath);
files = await Promise.all(
files.map(async (file) => {
const filePath = path.join(folderPath, file);
const stats = await fs.stat(filePath);
if (stats.isDirectory()) {
return getAllFile(filePath);
} else if (stats.isFile()) return filePath;
})
);
return files.reduce((all, folderContents) => all.concat(folderContents), []);
}
const filenames = new Set([
"index.html",
"index.htm",
"index.aspx",
"default.html",
"default.htm",
"default.aspx",
]);
const filterFiles = async (folderPath) => {
let filename, parts;
const paths = await getAllFile(folderPath);
const filteredFiles = paths.filter((filePath) => {
parts = filePath.split("/");
filename = parts[parts.length - 1];
return filenames.has(filename.toLowerCase());
});
return filteredFiles;
};
【问题讨论】:
标签: node.js async-await promise callback nodes