readdir withFileTypes Classifies Entries

List a directory with withFileTypes to receive Dirent objects, classifying files and folders by name without extra stat calls per entry.

JavascriptCli Tooling

Code

javascriptsnippet
16 lines
import { mkdir, writeFile, readdir } from 'node:fs/promises';

await mkdir('project/src', { recursive: true });
await writeFile('project/README.md', '# project');
await writeFile('project/src/app.js', 'export {}');

const entries = (await readdir('project', { withFileTypes: true })).sort((a, b) =>
  a.name.localeCompare(b.name),
);
for (const entry of entries) {
  console.log(entry.isDirectory() ? 'dir ' : 'file', entry.name);
}

// without withFileTypes you only get names, so type checks hit the disk again
const plainNames = await readdir('project');
console.log('plain names:', plainNames.sort());

Output

Captured from a sandboxed run of this snippet in the build pipeline.

file README.md
dir  src
plain names: [ 'README.md', 'src' ]

How it works

readdir withFileTypes Classifies Entries is built around the function entries.

Iteration happens inside for (const entry of entries) — everything outside it runs once. The asynchronous flow is linearized with await, keeping failure handling local. The only import source is node:fs/promises, a Node.js built-in, exposing mkdir, writeFile, readdir.

Points of care

  • The only import, node:fs/promises, is part of the Node.js standard library.

Applying it

Entry signature: const entries = (await readdir('project', { withFileTypes: true })

Output lines are prefixed (plain names:), making each step’s effect easy to spot.

Statements that matter

const entries = (await readdir('project', { withFileTypes: true })).sort((a, b) =>
  a.name.localeCompare(b.name),
);
await writeFile('project/src/app.js', 'export {}');
await writeFile('project/README.md', '# project');

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:fs/promises` ships with Node.js itself.