Node.js

List directory entries and their types

Pass withFileTypes to readdir when you need entry names and basic type checks. The returned Dirent objects can distinguish ordinary files and directories without first reading every file.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
  await fs.writeFile(join(directory, "note.txt"), "x");
  await fs.mkdir(join(directory, "images"));
  const entries = await fs.readdir(directory, {withFileTypes: true});
  console.log(entries.map(entry => `${entry.name}:${entry.isDirectory()}`).sort().join(","));
} finally {
  await fs.rm(directory, {recursive: true, force: true});
}

How it works

The example sorts its display output because directory enumeration order should not be treated as a presentation contract. IsDirectory describes the directory entry itself. Readdir is useful for one directory level; recursive traversal requires an additional deliberate policy.

Limits and mistakes

Symbolic links are their own entry type and may point outside the starting tree. Do not follow them unintentionally. Directory contents can also change after listing, so later operations still need normal error handling.

Check the result

Expect images:true,note.txt:false. Add another nested directory and confirm this listing does not automatically enumerate its children.

Sources

Reference documentation for the behavior used in this guide: