Directories: listing, creating and walking
A folder is a list of names, and the file system gives that list in whatever order it finds cheapest. readdir is the call that reads it, mkdir is the call that makes one, and withFileTypes is the option that says what each name is. None of the three recurses, so a walk over a tree is a function that calls itself.
The lesson lists a folder and sorts the result before printing it, creates a chain of folders with recursive, tells a file from a folder and ends with a walk that prints a small tree with two spaces of indent per level. Each program builds its tree inside a temporary folder and removes it at the end.
readdir
readdir(path) answers with an array of names: not paths, just the last component of each entry. The order is the order of the file system, so a program that prints or compares the list sorts it first. The lesson uses toSorted for that, which is the copying sort from the lesson on copying without mutation.
The program writes three files in an order that is not alphabetical and lists the folder, sorting the names before it prints them. The last check proves that every entry is a name and not a path.
The file readdir.mjs:
import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'dir-'));
await writeFile(join(dir, 'c.txt'), 'c');
await writeFile(join(dir, 'a.txt'), 'a');
await writeFile(join(dir, 'b.txt'), 'b');
const names = await readdir(dir);
console.log('the number of entries:', names.length);
console.log('sorted for printing:', names.toSorted().join(', '));
console.log('every entry is a name, not a path:', names.every((name) => !name.includes('/')));
await rm(dir, { force: true, recursive: true });
node readdir.mjs
the number of entries: 3
sorted for printing: a.txt, b.txt, c.txt
every entry is a name, not a path: true
The number of entries is what the folder holds and nothing more: no ., no .. and no parent. To read a file of that folder a program joins the folder with the name, which is the one thing readdir leaves to the caller.
mkdir with recursive
mkdir(path, { recursive: true }) creates every missing parent in the path, and it succeeds when the folder is already there. Without the option the call makes one level only and fails with EEXIST on an existing folder, which is the behaviour a script that must not reuse a folder wants.
The program creates a chain of three folders, calls the same line again, and then tries the call without the option on the folder that now exists. The listing of the first level proves the chain is there.
The file mkdir.mjs:
import { existsSync } from 'node:fs';
import { mkdir, mkdtemp, readdir, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'dir-'));
const deep = join(dir, 'reports', '2026', 'june');
await mkdir(deep, { recursive: true });
console.log('the whole chain exists:', existsSync(deep));
await mkdir(deep, { recursive: true });
console.log('a second call with recursive is fine');
try {
await mkdir(deep);
} catch (error) {
console.log('without recursive it fails with:', error.code);
}
console.log('reports holds:', (await readdir(join(dir, 'reports'))).join(', '));
await rm(dir, { force: true, recursive: true });
node mkdir.mjs
the whole chain exists: true
a second call with recursive is fine
without recursive it fails with: EEXIST
reports holds: 2026
The second call with recursive did nothing and did not fail, which is why a program can call it at start-up every time. The third call failed because the folder existed, and that is the same EEXIST the previous lesson used for the exclusive write flag.
withFileTypes
readdir(path, { withFileTypes: true }) answers with Dirent objects instead of names. Each one has a name and the methods isFile, isDirectory and isSymbolicLink, filled from the same call that listed the folder. Without the option a program would need one stat per entry, which is a system call per file.
The program lists a folder with one file and one folder, prints the two answers for each entry and then builds the same list with a slash after every folder.
The file types.mjs:
import { mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'dir-'));
await mkdir(join(dir, 'src'));
await writeFile(join(dir, 'notes.txt'), '');
await writeFile(join(dir, 'src', 'main.js'), '');
const entries = await readdir(dir, { withFileTypes: true });
entries.sort((left, right) => (left.name < right.name ? -1 : 1));
for (const entry of entries) {
console.log(entry.name, 'is a directory:', entry.isDirectory(), 'is a file:', entry.isFile());
}
const marked = entries.map((entry) => (entry.isDirectory() ? entry.name + '/' : entry.name));
console.log('with the folders marked:', marked.join(', '));
await rm(dir, { force: true, recursive: true });
node types.mjs
notes.txt is a directory: false is a file: true
src is a directory: true is a file: false
with the folders marked: notes.txt, src/
The sort by name puts the file before the folder here only because of the letters. A Dirent is a snapshot from the listing call: if the entry changes a moment later, the object still says what it said, which is fine for a report and not enough for a decision that must be atomic.
Walking a tree
A walk takes each directory entry, prints it, and calls itself for the entries that are folders. The function below sorts the entries at every level and adds two spaces to the indent, so the output is the usual tree and the order is the same on every machine. A deep tree could also be walked with an explicit stack, which Rust does in its lesson on paths and directory walks, but recursion is shorter and a filesystem is rarely deep enough to matter.
The program builds a tree with one file at the top, one in docs and two in src, then walks it from the root of the temporary folder.
The file walk.mjs:
import { mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const walk = async (dir, indent = '') => {
const entries = await readdir(dir, { withFileTypes: true });
entries.sort((left, right) => (left.name < right.name ? -1 : 1));
for (const entry of entries) {
const mark = entry.isDirectory() ? '/' : '';
console.log(indent + entry.name + mark);
if (entry.isDirectory()) {
await walk(join(dir, entry.name), indent + ' ');
}
}
};
const dir = await mkdtemp(join(tmpdir(), 'dir-'));
await mkdir(join(dir, 'src'));
await mkdir(join(dir, 'docs'));
await writeFile(join(dir, 'notes.txt'), '');
await writeFile(join(dir, 'docs', 'readme.md'), '');
await writeFile(join(dir, 'src', 'main.js'), '');
await writeFile(join(dir, 'src', 'util.js'), '');
console.log('the tree:');
await walk(dir);
await rm(dir, { force: true, recursive: true });
node walk.mjs
the tree:
docs/
readme.md
notes.txt
src/
main.js
util.js
The four files and the two folders came out in one order, and the indentation is the depth of each entry. The walk prints names and relative indentation and never a full path, which is the same rule the earlier programs followed: a printed path would differ on the machine of every reader.
Exercises
- List a folder and print only the names that end in .js. Which call do you need for the test?
- Create three nested folders with recursive and list the middle one. What does the listing hold?
- Print every entry of a folder with its size, using stat on the joined path. How many system calls does that take for ten files?
- Change the walk so that it prints the number of files instead of the tree. Where does the count live when the walk calls itself?
- What error does the walk get when it meets a folder it may not read? Which code does it carry, and what should the walk do with it?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does readdir return without any option?
Answer
An array of names
The names are the last component of each entry, and the folder is joined by the caller.
-
What does this program print?
import { mkdir, mkdtemp, readdir, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir = await mkdtemp(join(tmpdir(), "q-")); await mkdir(join(dir, "a", "b"), { recursive: true }); console.log((await readdir(join(dir, "a"))).join(",")); await rm(dir, { force: true, recursive: true });Answer
b
The listing of a holds the one folder that was created inside it.
-
What does this program print?
import { mkdir, mkdtemp, readdir, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir = await mkdtemp(join(tmpdir(), "q-")); await mkdir(join(dir, "src")); const entries = await readdir(dir, { withFileTypes: true }); console.log(entries.find((entry) => entry.name === "src").isDirectory()); await rm(dir, { force: true, recursive: true });Answer
true
The entry is a folder, and the method says so from the data of the listing.
-
What does mkdir with recursive true do when the folder already exists?
Answer
It succeeds and does nothing
That is the difference from the same call without the option, which fails with EEXIST.
-
What does this program print?
console.log(["b.txt", "a.txt", "c.txt"].toSorted().join(","));Answer
a.txt,b.txt,c.txt
toSorted returns a sorted copy, and the default order is by string.
-
What does isFile on a Dirent mean?
Answer
The entry is a regular file rather than a folder
The method describes the kind of the entry, and a symlink answers false to both isFile and isDirectory.
-
What does this program print?
import { mkdir, mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir = await mkdtemp(join(tmpdir(), "q-")); const child = join(dir, "reports"); await mkdir(child); try { await mkdir(child); } catch (error) { console.log(error.code); } await rm(dir, { force: true, recursive: true });Answer
EEXIST
The folder came from mkdtemp, and mkdir without recursive refuses an existing path.
-
In which order does readdir return the names?
Answer
In the order the file system gives them, so sort before printing
Nothing promises an order, which is why every program here sorts before it prints.
-
Does readdir walk into the folders it lists?
Answer
No, it lists one folder and leaves the recursion to the caller
A walk is a function of your own that calls readdir at every level.
-
What does withFileTypes save?
Answer
One stat call per entry
The kind of each entry comes with the listing instead of a call of its own.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev