Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
Sort files by extension with recursive function in js

I have a function which get me all the files in folder recursively but i want to sort them by only few specific extension , I know i can use glob but how do i do that using fs in node

const fs = require('fs');
function getFiles (dir, files_){
files_ = files_ || [];
var files = fs.readdirSync(dir);
for (var i in files){
    var name = dir + '/' + files[i];
    if (fs.statSync(name).isDirectory()){
        getFiles(name, files_);
    } else {
        files_.push(name);
    }
}
return files_;
}
console.log(getFiles('D:/sample'))
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could add conditional logic before pushing the files into files_ array, and then using string methods to check the last 4 elements of files[i] if it matches a certain extension, and if it does, proceed to push that file into files_.

  const fs = require('fs');
  function getFiles (dir, files_) {
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    var parseThese = [".txt", ".pdf", ".csv"];
    
    for (var i in files) {
      var name = dir + '/' + files[i];
      var extension = "";

      if (fs.statSync(name).isDirectory()) {
        return getFiles(name, files_);
      } 

      extension = files[i].slice(-4);
      if (parseThese.includes(extension)) {
        return files_.push(name);
      }
    }
    return files_;
 }
 console.log(getFiles('D:/sample'))

It's not using the FS module, but perhaps this could work.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!