Answered
I have a directory that I'm trying to examine with Node.js.
When I give Node.js a directory, how can I get it retrieve a list of each file in that directory? And I'd like to include any files that are inside child directories. So, the solution will need to be recursive.
Thanks for the help in advance!
Here's a function that takes a directory path and recursively gets all the files in it (including child directories):
const getAllFiles = function(dirPath, arrayOfFiles) {
files = fs.readdirSync(dirPath)
arrayOfFiles = arrayOfFiles || []
files.forEach(function(file) {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles)
} else {
arrayOfFiles.push(path.join(__dirname, dirPath, "/", file))
}
})
return arrayOfFiles
}
Code breakdown:
readdirSync()
method to get all the files and directories in the given directory path.arrayOfFiles
) that will hold all the file paths that will be returned when the function is complete.arrayOfFiles
array.forEach()
loop is complete, we return the arrayOfFiles
. This contains all the file paths.You can use the function like this:
getAllFiles("path_to_directory")
/*
[
'/path/to/file',
'/path/to/file',
'/path/to/file',
. . .
]
*/