Interview Q&A / Node.js

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you list all files in a folder and its subfolders in Node.js?

SHORT ANSWER

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

js
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:

js
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 stat on every entry when withFileTypes already gives the type.
  • Following symlinks into endless loops.

#nodejs#fs

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.