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
Periodic Table Chart, 33.1 x 23.4 in (84.1 x 59.4 cm, Poster / Wall Chart), 18-Column Layout, Zulu-Labeled
2027 Wall Calendar, Altai/English-Labeled, Monday-Start Layout, Wire-Bound, 11.7 x 8.3 in (29.7 x 21.0 cm)
Ursa Major Constellation Poster, Luxembourgish-Labeled
orchestra IPA Transcription Poster