Skip to content

Instantly share code, notes, and snippets.

@DawnImpulse
Created October 5, 2018 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DawnImpulse/e58e6bfa1d7152d0aa14b3af278c3b12 to your computer and use it in GitHub Desktop.
Save DawnImpulse/e58e6bfa1d7152d0aa14b3af278c3b12 to your computer and use it in GitHub Desktop.
list all files in a directory recursively
// credits - https://www.codexpedia.com/node-js/node-js-getting-files-from-a-directory-including-sub-directories/
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment