如何使用nodejs检查数组列表中存在的具有给定扩展名的文件

How to check file with given extension which are present in array list using nodejs

我想检查名称存在于数组中且仅 select 存在于数组列表中但具有 if 条件的文件夹 和 return FileArray

中存在的值
let extensionArray = [".html", ".htm", ".aspx"];
  let fileArray = [
    "index.html",
    "index.htm",
    "index.aspx",
    "Index.html",
    "Index.htm",
    "Index.aspx",
    "default.html",
    "default.htm",
    "default.aspx",
    "Default.html",
    "Default.htm",
    "Default.aspx",
  ];

if(!extensionArray.include(true){
if(!fileArray.inclue(true){
// return the output 
}
}

我检查了其中一个 post,其中可以从所有文件夹和子文件夹中检查文件

但我不知道在哪里应用我的条件来检查扩展名和文件名,然后 return 它。

代码如下:-

const fs = require('fs');
const path = require('path');

async function getFile(dir) {
  let files = await fs.readdir(dir);
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(dir, file);
      const stats = await fs.stat(filePath);
      if (stats.isDirectory()) return getFile(filePath);
      else if (stats.isFile()) return filePath;
    })
  );

  return files.reduce((all, folderContents) => all.concat(folderContents), []);
}

您不必将大写和小写形式的文件名都添加到 fileArray。过滤文件时,您可以将文件名转换为小写。您可以将文件名添加到 Set。此外,您不需要 extensionArray 因为您将直接检查文件名。通过调用 getFilePaths 函数获得目录中的文件路径列表后,您可以通过检查小写文件名(通过 / 拆分文件路径并获取中的最后一个元素来获得)来过滤它们数组)存在于集合中。

const fs = require('fs').promises
const path = require('path')

const filenames = new Set([
  'index.html',
  'index.htm',
  'index.aspx',
  'default.html',
  'default.htm',
  'default.aspx',
])

const getFilePaths = async (dir) => {
  let files = await fs.readdir(dir)
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(dir, file)
      const stats = await fs.stat(filePath)
      if (stats.isDirectory()) {
        return getFilePaths(filePath)
      }
      return filePath
    })
  )

  return files.flat()
}

const filterFiles = async (dir) => {
  const paths = await getFilePaths(dir)
  const filteredFiles = paths.filter((filePath) => {
    const parts = filePath.split('/')
    const filename = parts[parts.length - 1]
    return filenames.has(filename.toLowerCase())
  })
  console.log(filteredFiles)
}

filterFiles('.')