How do you list all files in a folder and its subfolders in Node.js?
Use fs.promises.readdir with the recursive option on recent Node versions, or write a small recursive function using withFileTypes to tell files from directories.
Explain it simply
To list everything in a college campus folder, you open each room, note the files, and when you find another folder, you do the same inside it. That repeated "do the same inside" is recursion.
Example
const fsp = require("fs/promises");
const path = require("path");
async function walk(dir) {
const entries = await fsp.readdir(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await walk(full)));
} else {
files.push(full);
}
}
return files;
}
walk("./uploads").then((list) => console.log(list));withFileTypes: true returns Dirent objects, so you know whether each item is a file or a folder without another stat call.
On Node 18.17 and newer, there is a shortcut:
const names = await fsp.readdir("./uploads", { recursive: true });It returns paths relative to the starting folder. Symbolic links can cause loops in a hand-written walker, so skip them or track visited folders if links are possible.
What to say in the interview
"I read the directory with withFileTypes, recurse into subdirectories and collect files. Newer Node has readdir with recursive: true, which does it in one call."
Common mistakes
- Calling
staton every entry whenwithFileTypesalready gives the type. - Following symlinks into endless loops.