按扩展名数组输出目录中的文件列表

output list of files in a directory by array of extensions

我试图只获取图像文件名以从给定目录输出到控制台。 我最初是在关注这个答案,但我不知道如何给它多个扩展名。

function fName(fp){
    const { readdirSync } = require('fs');
    const path = require("path");
    const fs = require('fs');
    
    // dont need whole filepaths atm
    // const gl = require('glob');
    
    //gl(fp + `/**/*.@(jpg|png)`, {}, (err, files) => {
    //  console.log(files)
    // })

    let extensions = ["jpg", "jpeg", "png"];

    let nameFilter = [];
    const rawFileNames = readdirSync(fp, {withFileTypes: true})
    .filter(dirent => dirent.isFile())
    .map(dirent => dirent.name)

    //filter the extensions
    let fileNames = rawFileNames.filter(file => {
        path.extname(file).toLowerCase() === extensions;
    })

    console.log(fileNames);

    
}

编辑

我也只是尝试创建一个遍历扩展列表并调用它的函数,但它仍然returns一个空数组

 let extensions = ["jpg", "jpeg", "png"];

        let getexts = function(exte){
            for (ex in exte){
                return exte[ex];
            }
        }

        let nameFilter = [];
        const rawFileNames = readdirSync(fp, {withFileTypes: true})
        .filter(dirent => dirent.isFile())
        .map(dirent => dirent.name)

        //filter the extensions
        let fileNames = rawFileNames.filter(file => {
            path.extname(file).toLowerCase() === getexts(extensions);
        })

在你的过滤器中,你不能只做:

let fileNames = rawFileNames.filter(file => {
    return extensions.includes(path.extname(file).toLowerCase())
})

按如下方式修改您的文件管理器条件。

//filter the extensions
let fileNames = rawFileNames.filter(file => {
  return extensions.includes(path.extname(file).toLowerCase())      
});

console.log(fileNames);