Walking a directory 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");Recommended for you
Product
Ea.
"Hello, World!" Code Snippet Poster, JavaScript Programming Language
Solar System Poster, Norwegian-Labeled
Khakas Alphabet Chart, 23.4 x 33.1 in (59.4 x 84.1 cm, Poster / Wall Chart), Dutch-Labeled
Phenolphthalein Molecule Poster, Ball-and-Stick Model, Korean-Labeled
2026 Wall Calendar, Tahitian-Labeled, Monday-Start Layout, Poster / Wall Print, 23.4 x 33.1 in (59.4 x 84.1 cm)