You can use the built-in fs
module in Node.js to list all the files in the current directory and all subdirectories recursively. Here is a sample code to achieve this:
index.tsx442 chars23 lines
The getFiles
function accepts a directory path and an optional file list array as parameters. It uses fs.readdirSync
to read the contents of the directory and path.join
to generate the file path.
For each file in the directory, the function checks if it's a directory or a file. If it's a directory, it calls itself recursively with the path of the subdirectory. If it's a file, it adds the file path to the file list array.
Finally, the function returns the file list array. To use this function, simply call it with the current directory path (__dirname
in Node.js) and it will return an array with all the file paths in the current directory and all subdirectories.
gistlibby LogSnag