List each file in a directory using Node.js? Including child directories?

Answered
looper003 asked this question 1 year, 5 months ago
looper003 on Dec 13, 2021 · Edited

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!

1 suggested answers
suparman21 on Dec 17, 2021 · Edited

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:

  • Use the readdirSync() method to get all the files and directories in the given directory path.
  • We create an array of files (arrayOfFiles) that will hold all the file paths that will be returned when the function is complete.
  • Loop over each file or directory that was found. If the item is a directory, the function recursively calls itself to get all the files and sub-directories in that given directory. If the item is a file, we add the file path to the arrayOfFiles array.
  • When the 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',

  . . .

]
*/
0 replies
Answered