Home > Enterprise >  output list of files in a directory by array of extensions
output list of files in a directory by array of extensions

Time:09-22

I'm trying to get only image filenames to output into console from a given directory. I was originally following this answer but I couldn't figure out how to give it multiple extensions.

How do I get a list of files with specific file extension using node.js?

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);

    
}

EDIT

I also just attempted to make a function that iterates over the extension list and call it, but it still returns an empty array

 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);
        })

CodePudding user response:

In your filter, couldn't you just do:

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

CodePudding user response:

Modify your filer condition as below.

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

console.log(fileNames);
  • Related