How to list all files recursively within a directory tree in Node.js?
To recursively walk through the directory tree and get the path of each file in the tree, use the following code snippet:
const fs = require("fs");
const path = require("path");
function walkDirectory(directoryPath: string) {
return fs.readdirSync(directoryPath).flatMap((fileOrSubdirectory) => {
const fileOrSubdirectoryPath = path.join(directoryPath, fileOrSubdirectory);
if (fs.statSync(fileOrSubdirectoryPath).isDirectory()) {
return walkDirectory(fileOrSubdirectoryPath);
}
return [fileOrSubdirectoryPath];
})
};
const files = walkDirectory("/path/to/directory");
Thanks for stopping by my digital playground! If you want to say hi, you can reach out to me on LinkedIn or via email. I'm always keen to chat and connect.
If you really-really like my work, you can support me by buying me a coffee.