Node.js Reference ยท fs and fs/promises
The fs.Dirent class
Reference for fs.Dirent in Node.js: the objects returned by readdir withFileTypes and opendir, name and parentPath, type checks and why they beat stat.
An fs.Dirent (directory entry) is a lightweight object that stands for one item found inside a directory. fs.readdir() returns them when you pass withFileTypes: true, and fs.opendir() yields them as you iterate.
A Dirent holds the entry's name, the folder it was found in and its type. The operating system usually reports the type while listing, so asking entry.isDirectory() costs nothing, whereas calling stat on each name means one extra system call per entry.
import fs from "node:fs"; for (const entry of fs.readdirSync(".", { withFileTypes: true })) { console.log(entry.name, entry.isDirectory()); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
class Dirent { name: string | Buffer // entry name, no directory part parentPath: string // directory that contains the entry isFile(): boolean isDirectory(): boolean isSymbolicLink(): boolean isBlockDevice(): boolean isCharacterDevice(): boolean isFIFO(): boolean isSocket(): boolean }
| Member | Description |
|---|---|
name |
The file name only. It is a Buffer if you listed with encoding: "buffer". |
parentPath |
The directory holding the entry. For a non-recursive listing it is the path you passed in. For a recursive listing it is the actual subfolder. Added in Node 20.12 and 21.4. |
is*() |
Type checks, exactly like the same methods on fs.Stats, but computed from the directory listing. |
Usage notes
- Full path =
path.join(entry.parentPath, entry.name). Using the name alone in a recursive listing points at the wrong place. - Older code uses
entry.path, an earlier name forparentPath. It is deprecated and not present on current Node 24 objects, so useparentPath. - Links are not followed. A symbolic link to a folder reports
isSymbolicLink()astrueandisDirectory()asfalse. Callfs.stat()on the joined path if you need the target's type. - Exactly one check is true for ordinary entries, so a chain of
if/else ifis safe. Always include a fallback for sockets and devices. - Snapshot only. The type was read at listing time; the entry may have changed since.
- No size or times. For those, call
fs.stat()on the joined path. - Do not construct it yourself; it comes from
readdirandopendir.