Skip to content
Advertisement

Count all files with specific type in folder

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement