Home > Enterprise >  Count all files with specific type in folder
Count all files with specific type in folder

Time:11-07

I'm kinda new to coding, and I need to count files with specific type in my folder, but I don't know how to do it using fs module!

My current code:

const fs = require('fs'); 
fs.readdir(dir, (err, files) => {
    console.log(files.length)
});

Can someone help me?

CodePudding user response:

You can use path.extname like this:

const fs = require('fs'); 
const path = require('path');
fs.readdir(dir, (err, files) => {
    const result = files.filter(f => path.extname(f).toLowerCase() === yourExtension).length
    console.log(result)
});

Also, as mentioned by MegaMix_Craft, take care about the variable yourExtension. It has to have the dot .value. As an example it should be .js not only js.

  • Related