node.js getting files from a directory including sub-directories

The node.js code snippet below walks through all the directories in the provided directory and returns all the files specified in the fileTypes. It reads the files from the initial directory, if it’s a file then add it to the global array to save the file path, else if it is a directory, recursively call the walkDir function to look deeper in the subdirectory for the files you are searching for.

var fs = require('fs');
var path = require('path');

// Return a list of files of the specified fileTypes in the provided dir, 
// with the file path relative to the given dir
// dir: path of the directory you want to search the files for
// fileTypes: array of file types you are search files, ex: ['.txt', '.jpg']
function getFilesFromDir(dir, fileTypes) {
  var filesToReturn = [];
  function walkDir(currentPath) {
    var files = fs.readdirSync(currentPath);
    for (var i in files) {
      var curFile = path.join(currentPath, files[i]);      
      if (fs.statSync(curFile).isFile() && fileTypes.indexOf(path.extname(curFile)) != -1) {
        filesToReturn.push(curFile.replace(dir, ''));
      } else if (fs.statSync(curFile).isDirectory()) {
       walkDir(curFile);
      }
    }
  };
  walkDir(dir);
  return filesToReturn; 
}

//print the txt files in the current directory
getFilesFromDir("./", [".txt"]).map(console.log);

Search within Codexpedia

Custom Search

Search the entire web

Custom Search