Created
October 5, 2018 05:33
-
-
Save DawnImpulse/e58e6bfa1d7152d0aa14b3af278c3b12 to your computer and use it in GitHub Desktop.
list all files in a directory recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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