Skip to content
jshacks.dev
Node.js

fs.promises.opendir() in Node.js Explained With Examples

Iterate a folder one entry at a time with fs.promises.opendir in Node.js 24 and 26: async iteration, Dir.close, bufferSize, recursive and readdir.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript and RabbitMQ logos.

readdir reads a whole folder into an array before you see the first name. For a folder with ten files that is perfect. For a folder with a million entries, such as a cache, a mail spool or a photo dump, building one huge array wastes memory and delays the first result. fs.promises.opendir opens the folder as a handle and lets you read entries one at a time with for await, so you can start work immediately, stop early and keep memory flat. This post covers opendir from node:fs/promises on Node.js 24 and 26: the basic loop, the Dir object and when it closes, bufferSize, the recursive option, ordering, stopping early, and how it differs from readdir and glob. It pairs with readdir and glob. Samples build a small tree in a temporary folder and sort their output, because the order of entries is decided by the file system.

The tree used in the samples

Text
data/
  a.txt
  b.txt
  c.log
  inner/
    d.txt
setup.mjsJavaScript
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

export async function makeData() {
  const root = await mkdtemp(join(tmpdir(), "dir-"));
  const data = join(root, "data");
  await mkdir(join(data, "inner"), { recursive: true });
  await writeFile(join(data, "a.txt"), "a");
  await writeFile(join(data, "b.txt"), "b");
  await writeFile(join(data, "c.log"), "c");
  await writeFile(join(data, "inner", "d.txt"), "d");
  return data;
}

The basic loop

opendir(path[, options]) resolves with a Dir object, which is an async iterable of Dirent entries. Loop over it with for await.

basic.mjsJavaScript
import { opendir } from "node:fs/promises";
import { makeData } from "./setup.mjs";

const data = await makeData();
const rows = [];

const dir = await opendir(data);
for await (const entry of dir) {
  rows.push(`${entry.name} ${entry.isDirectory() ? "dir" : "file"}`);
}

console.log(rows.sort().join("\n"));
Text
a.txt file
b.txt file
c.log file
inner dir

Each entry is a Dirent with name, the parent folder in parentPath, and methods such as isFile() and isDirectory(). The type comes from the directory listing itself, so there is no extra stat call per entry. The array in the sample is only for printing in sorted order; real code would act on each entry as it arrives.

Closing is handled for you, mostly

When a for await loop finishes or ends early through break, return or a thrown error, the iterator closes the Dir automatically. You only call dir.close() yourself when you read entries manually with dir.read() and stop before the end.

early.mjsJavaScript
import { opendir } from "node:fs/promises";
import { makeData } from "./setup.mjs";

const data = await makeData();
let seen = 0;

for await (const entry of await opendir(data)) {
  seen += 1;
  if (seen === 2) break;
}

console.log(seen);
Text
2

The loop stopped after two entries, and the folder handle was released by the break. Stopping early is the main advantage over readdir: finding the first file that matches a condition costs only as many reads as it takes to find it.

Reading manually with read

You can drive the Dir yourself. dir.read() resolves with the next Dirent, or null when the end is reached, and dir.close() releases the handle.

manual.mjsJavaScript
import { opendir } from "node:fs/promises";
import { makeData } from "./setup.mjs";

const data = await makeData();
const dir = await opendir(data);
const names = [];

let entry;
while ((entry = await dir.read()) !== null) {
  names.push(entry.name);
}
await dir.close();

console.log(names.sort());
Text
[ 'a.txt', 'b.txt', 'c.log', 'inner' ]

Calling close() twice raises an error with the code ERR_DIR_CLOSED, so close once, ideally in a finally block, if you are not using for await. With the loop, none of this bookkeeping is needed.

Filtering as you go

Because entries arrive one by one, a filter can run before you accumulate anything. This sample counts the .txt files without ever holding the full list.

filter.mjsJavaScript
import { opendir } from "node:fs/promises";
import { extname } from "node:path";
import { makeData } from "./setup.mjs";

const data = await makeData();
let count = 0;

for await (const entry of await opendir(data)) {
  if (entry.isFile() && extname(entry.name) === ".txt") count += 1;
}

console.log(count);
Text
2

Only a.txt and b.txt count, since d.txt lives in a subfolder that this non-recursive call does not visit.

The recursive option

opendir(path, { recursive: true }) walks into subfolders too. Each entry's parentPath tells you where it lives, so you can rebuild the full path. The recursive option was added in Node.js 20.1 and 18.17, so it is available on current versions, and the fs documentation describes it.

recursive.mjsJavaScript
import { opendir } from "node:fs/promises";
import { join, relative } from "node:path";
import { makeData } from "./setup.mjs";

const data = await makeData();
const paths = [];

for await (const entry of await opendir(data, { recursive: true })) {
  paths.push(relative(data, join(entry.parentPath, entry.name)));
}

console.log(paths.sort().join("\n"));
Text
a.txt
b.txt
c.log
inner
inner/d.txt

The entry for the folder inner appears as well as its content. The order across levels is not defined, so sort when you need a fixed order. Use parentPath rather than the older path property, which is deprecated in favor of it.

The bufferSize option

Internally, the directory is read in batches, and bufferSize sets how many entries are fetched at a time. The default is 32. A larger value means fewer round trips to the operating system on huge folders at the cost of a little more memory, and a smaller value does the opposite. Most programs never change it, and the right value for a particular folder is something to measure, not guess.

buffer.mjsJavaScript
import { opendir } from "node:fs/promises";
import { makeData } from "./setup.mjs";

const data = await makeData();
let count = 0;

for await (const entry of await opendir(data, { bufferSize: 64 })) {
  count += 1;
}

console.log(count);
Text
4

The result is the same for any buffer size. Only the rhythm of the reads changes.

Errors

A missing path or a path that is not a folder rejects when you call opendir, before any entry is read.

errors.mjsJavaScript
import { opendir, writeFile, mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

try {
  await opendir("/no/such/folder");
} catch (err) {
  console.log(err.code);
}

const dir = await mkdtemp(join(tmpdir(), "dir-"));
await writeFile(join(dir, "file.txt"), "x");

try {
  await opendir(join(dir, "file.txt"));
} catch (err) {
  console.log(err.code);
}
Text
ENOENT
ENOTDIR

ENOENT means nothing is there, and ENOTDIR means the path exists but is a file. Handle both with a clear message that names the path.

opendir, readdir or glob

NeedUse
Names in a small folderreaddir
Names plus types for a small folderreaddir with withFileTypes: true
Huge folder, memory matters, stop earlyopendir
Pattern like **/*.jsglob
Whole tree as one listreaddir with recursive: true

readdir is simpler and almost always right. Reach for opendir when a folder may be large enough that holding the whole listing is a cost, or when you want to quit as soon as you find what you need.

Common mistakes

  • Forgetting to await the call and iterating over a promise. Write for await (const e of await opendir(p)), or keep the Dir in a variable first.

  • Assuming sorted output. The file system sets the order.

  • Calling dir.close() after a loop that already closed it, which raises ERR_DIR_CLOSED.

  • Building paths with entry.name alone in a recursive walk. Join parentPath and name.

  • Using the deprecated entry.path.

  • Using opendir for tiny folders, which adds code without any benefit.

A worked example: find the first large file

A cleanup script might need the first file bigger than a limit. With opendir it stops as soon as it finds one.

firstlarge.mjsJavaScript
import { opendir, stat } from "node:fs/promises";
import { join } from "node:path";
import { makeData } from "./setup.mjs";

const data = await makeData();

async function firstLargerThan(folder, bytes) {
  for await (const entry of await opendir(folder)) {
    if (!entry.isFile()) continue;
    const { size } = await stat(join(folder, entry.name));
    if (size > bytes) return entry.name;
  }
  return null;
}

console.log(await firstLargerThan(data, 100));
Text
null

Every file in the sample holds one byte, so none passes the limit, and the function returns null after reading all entries. On a real folder with a large file, it would return at the first match without reading the rest.

A note on large folders

Folders with very many entries behave differently from small ones, and this is where opendir pays off. Listing a million names with readdir allocates a million strings or objects at once, and the first result is not available until the whole listing has been read. With opendir you can print progress, apply a limit, and stop as soon as you have what you need. Combine it with a counter to take a sample of the first N entries, or with stat calls to find the oldest file without keeping every name. Remember that the number of operating system calls is roughly proportional to the number of entries either way, so opendir saves memory and latency, not total work. If you run a stat on every entry, consider limiting how many run at the same time, since thousands of concurrent calls compete for the thread pool. Process entries sequentially in the loop, or in small batches, and the folder walk stays predictable under load. For ordinary application folders with a handful of files, none of this matters and readdir is the better, shorter choice.

Also inAsync
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.