如何使用node js过滤多个扩展文件

How to filter multiple extension files using node js

我想过滤掉数组中提到的一些文件,但不知道如何过滤

我看过一个 post 但它只显示一个扩展 如何过滤它 如果有扩展数组怎么办

async function getAllFile(folderPath, depth) {
  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() && depth > 0) {
        return getAllFile(filePath, depth - 1);
      } else if (stats.isFile()) return filePath;
    })
  );

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

const filenames = new Set([
".html",
".htm",
".aspx"
])

const filterFiles = async (folderPath) => {
  let filename,
    parts;
  const paths = await getAllFile(folderPath);
  
  const filteredFiles = [];
  const otherFiles = [];
  for (const filePath of paths) {
    parts = filePath.split("/");
    filename = parts[parts.length - 1];
    if (filenames.has(filename.toLowerCase())) {
      filteredFiles.push(filePath);
    } else {
      otherFiles.push(filePath);
    }
  }
  return { filteredFiles, otherFiles }; 
};

任何解决方案如何解决这个问题

您可以使用 Array.filterString.lastIndexOfString.substr & Array.includes

获取所有匹配有效扩展名的文件

以下方法只会 return 匹配的扩展名。

let files = ["abc.txt", "/test/abc.htm", "/etc/dev/xyz.html"];

const allowedExtensions = [ ".html", ".htm", ".aspx"];

const filterFiles = (files, allowedExtns) => {
  return files.filter(file => {
  //Find the last index of '.'
    const lastIndex = file.lastIndexOf(".");
    //If last index of '.' is not -1 then
    //take the substring from that index till the end and 
    //check in the allowedExnts array 
    return lastIndex !== -1 && allowedExtns.includes(file.substr(lastIndex))
  })
}

console.log(filterFiles(files, allowedExtensions));

但是,如果您希望同时获得有效和无效的,那么下面的方法将会有所帮助

let files = ["abc.txt", "/test/abc.htm", "/etc/dev/xyz.html"];

const allowedExtensions = [ ".html", ".htm", ".aspx"];

const filterFiles = (files, allowedExtns) => {
  return files.reduce((acc, file) => {
    const lastIndex = file.lastIndexOf(".");
     //If last index of '.' is not -1 then
     //take the substring from that index till the end and 
     //check in the allowedExnts array & if the result is true
     //then add to `valid` array in the `acc` otherwise
     //add to `invalid` array in the `acc`
    if(lastIndex !== -1 && allowedExtns.includes(file.substr(lastIndex))) {
      acc.valid.push(file);
    } else{
      acc.invalid.push(file);
    }
    return acc;
  }, {valid: [], invalid: []})
}

console.log(filterFiles(files, allowedExtensions));

试试这个

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

const getAllFile = async (folderPath) => {
  let files = fs.readdirSync(folderPath);
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(folderPath, file);
      const stats = fs.statSync(filePath);
      if (stats.isDirectory()) {
        return await getAllFile(filePath);
      } else if (stats.isFile()) return filePath;
    })
  );
  return files.reduce((all, folderContents) => all.concat(folderContents), []);
};

const fileExtensions = [
  ".html",
  ".htm",
  ".aspx",
  // Add your extensions here which you need to see in filteredFiles and don't need in otherFiles
];

const filenames = [
  "index",
  "default",
  // Add your fine names here which you need to see in filteredFiles
];

const filterFiles = async (folderPath) => {
  let filename, parts;
  const paths = await getAllFile(folderPath);
  const filteredFiles = [];
  const otherFiles = [];
  const ignoredFiles = [];
  for (const filePath of paths) {
    parts = filePath.split("/");
    filename = parts[parts.length - 1].split(".")[0];
    let splitFileName = parts[parts.length - 1].split(".");
    if (
      fileExtensions.includes(`.${splitFileName[splitFileName.length - 1]}`)
    ) {
      if (filenames.includes(filename.toLowerCase())) {
        filteredFiles.push(filePath);
      } else {
        ignoredFiles.push(filePath);
      }
    } else {
      otherFiles.push(filePath);
    }
  }
  return { filteredFiles, otherFiles, ignoredFiles };
};

filterFiles("./test")
  .then(({ filteredFiles, otherFiles, ignoredFiles }) => {
    console.log("filteredFiles:::", filteredFiles);
    console.log("otherFiles:::", otherFiles);
    console.log("ignoredFiles:::", ignoredFiles);
  })
  .catch((e) => console.log("ERRROR::", e));