Directory entries and file handles
Local practice: Node.js 22.16.0 and npm 10.9.2 on Linux x64; proposed teaching baseline 26.13.1 LTS remains untested. Use a fresh disposable folder for each example, copy only the shown files and run the fixed command. No packages or external services required. Static examples are not ByteMind runner support. The archive is author-only; do not copy expected.json into the example directory.
List owned fixture entries
import { readdir } from "node:fs/promises";const entries = await readdir(".", { withFileTypes: true });const files = entries.filter(entry => entry.isFile()).map(entry => entry.name).sort();console.log(files.join(", "));Run in this fixture directory:
node main.mjsExpected stdout:
a.txt, b.txt, main.mjsExpected exit status: 0. Expected stderr: empty. The fixture has two text files and the script. Sorting makes the output independent of directory iteration order.
How it works
readdir(path, { withFileTypes: true }) returns Dirent objects with names and predicates such as isFile. Directory iteration order is not a reliable sorting contract; sort explicitly. stat follows symbolic links while lstat describes the link itself. open(path, flags) in node:fs/promises returns a FileHandle; close it in finally. File handles also expose operations such as stat and readFile. Closing an open handle is separate from deleting the file. A preceding stat is not a guarantee of later path identity, and a handle can outlive a name change on some filesystems.
Close a file handle reliably
import { open } from "node:fs/promises";const handle = await open("sample.txt", "r");try { const info = await handle.stat(); console.log(info.isFile(), info.size); console.log(await handle.readFile("utf8"));} finally { await handle.close();}Run in this fixture directory:
node main.mjsExpected stdout:
true 4bookExpected exit status: 0. Expected stderr: empty. The four ASCII bytes form the text book. The finally block closes the handle on success or failure.
Common mistake
Do not open handles in an unbounded loop or leave closing to garbage collection. Do not assume all directory entries are regular files or follow untrusted links.
Try it yourself
In a new fixture directory with one file and one nested directory, list only file names sorted. Open the file read-only, print its contents, then close the handle even if parsing fails.
Further reading: Official documentation 1. Related ByteMind reference candidate: node-fs-promises-open (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Directory entries and file handles — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
How can directory output be made predictably alphabetical?
Which call describes a symbolic link itself?
Where should a FileHandle be closed?