Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 133 ยท File System

Directories, Stats and Watching

Work with folders in Node.js - mkdir recursive, readdir with withFileTypes, stat and lstat, rm, cp, rename, fs.glob, fs.watch caveats, and walking a directory tree with async iteration.

Files live in directories, and real programs spend as much time listing, creating, moving and measuring them as reading their content. A build tool walks a source tree. A backup tool copies a folder. An upload handler creates a directory per user. A dev server watches files for changes. In Node.js all of this is in node:fs/promises, next to the file functions from Reading and Writing Files.

In this lesson you will create and list directories, find out what an entry is (file, folder, link) and how big it is with stat, delete and copy trees, rename and move, match files with fs.glob, understand what fs.watch can and cannot promise, and write a recursive tree walker with an async generator. All examples create their own files, because the sandbox starts empty on every run.

Creating directories

mkdir(path) creates one directory and fails with ENOENT if the parent is missing, or with EEXIST if the directory is already there. The option { recursive: true } changes both rules: it creates all missing parents (like mkdir -p on the command line) and does not complain if the directory already exists. That makes it the right way to "make sure this folder exists".

Node.js mkdir and recursive

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.

With recursive: true, mkdir returns the path of the first directory it had to create (or undefined if everything existed). That is handy when you want to clean up afterwards.

Listing a directory with readdir

readdir(path) returns an array of names, not full paths. The order is whatever the operating system returns, which is not guaranteed to be alphabetical on every platform. If order matters, sort the result yourself.

Names alone do not tell you whether an entry is a file or a folder. Pass { withFileTypes: true } and you get Dirent objects that carry the type without an extra stat call, and with { recursive: true } you get the whole subtree at once.

Node.js readdir, Dirent and recursive listing

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.

The Dirent methods are isFile(), isDirectory(), isSymbolicLink() and a few rarer ones. parentPath (Node 20.12+; older code used path) tells you the directory that contains the entry, which you need with recursive: true.

There is also opendir(path), which returns a Dir object you can iterate lazily with for await. Use it for directories with millions of entries, where readdir would build one gigantic array.

opendir and Dir: lazy listing and typed entries

readdir reads the whole directory before it gives you anything. opendir returns a Dir object that hands out entries one at a time, so memory stays flat even for a folder with millions of files, and you can stop early. A Dir is an async iterable of Dirent objects, and it must be closed (iterating to the end closes it automatically; await dir.close() after an early break or in a finally block).

A Dirent is a directory entry with a name and a type that the operating system already supplied, so asking isFile() costs no extra system call. The type checks are isFile(), isDirectory(), isSymbolicLink(), isFIFO(), isSocket(), isBlockDevice() and isCharacterDevice(). Exactly one of them is true for a normal entry. Remember that a Dirent describes the entry itself, as lstat does: a symlink to a directory is a symbolic link, not a directory. The properties are name and parentPath (the folder that contains it).

Node.js opendir, Dir and Dirent type checks

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.

Use readdir(path, { withFileTypes: true }) for ordinary folders (simpler, one call) and opendir when the folder can be enormous or you want to stop after the first match. Neither promises an order, so sort if the order matters. For a recursive walk see the tree walker later in this lesson.

Stat: size, type and times

stat(path) returns a Stats object describing the file system entry. The most used properties are size (bytes), mtime (last content change), birthtime (creation, not available on every file system), mode (permission bits) and the type methods isFile(), isDirectory() and isSymbolicLink().

stat follows symbolic links and describes the target. lstat describes the link itself. Choose lstat whenever you walk directory trees, otherwise a link that points to its own parent makes you loop forever.

Node.js stat and lstat

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.

The option { throwIfNoEntry: false } makes stat resolve to undefined instead of rejecting when the path is missing (it started on the synchronous statSync, and the promise version accepts it in Node.js 24 as the last line shows; on older versions catch ENOENT). If the sandbox you run in forbids symbolic links, the symlink call fails with a permission error; here it works. Times are Date objects (also available as numbers in mtimeMs). Do not print real timestamps of files you just created in examples or tests; they change on every run.

Deleting: rm and rmdir

Use rm(path, options) for everything. Without options it removes a single file. For directories you must opt in:

  • { recursive: true } removes a directory and everything inside it.
  • { force: true } makes a missing path not an error (like rm -f).

rmdir still exists but only removes empty directories and is rarely what you want. The old { recursive: true } option of rmdir is deprecated; use rm.

Node.js rm with recursive and force

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.

The error for a directory without recursive is ERR_FS_EISDIR (Node's own code, not an operating-system code). Be careful: rm(userInput, { recursive: true, force: true }) is a great way to delete things you did not intend to. Validate and resolve paths first (Paths, Permissions and Safe File Handling).

Copying and moving

cp(source, destination, options) copies files and, with { recursive: true }, whole directory trees. copyFile(source, destination) copies a single file and can refuse to overwrite with the COPYFILE_EXCL mode. rename(oldPath, newPath) moves or renames in place, and replaces an existing file at the destination.

Node.js cp, copyFile and rename

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.

The filter function in the last step receives each source path and returns true to copy it. It skips main.css, but the css folder itself still gets copied (empty), because its name does not end in .css. Filtering decides per entry; it does not prune by content.

Two traps with rename: it works only inside one file system (moving to another disk fails with EXDEV; copy and then remove instead), and on most systems it silently replaces an existing destination file. cp with { recursive: true } is considered stable since Node 22.3; older versions marked it experimental.

Finding files with fs.glob

A glob is a pattern such as src/**/*.js: * matches any characters within one path segment, ** matches any number of nested directories, and ? matches one character. fs.glob (Node 22+) returns an async iterator of matching paths, so you no longer need an npm package for simple cases. The function is still marked experimental in some versions of the documentation, so verify it in the runtime you deploy to.

Node.js fs.glob

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.

Patterns can be a single string or an array. The exclude option takes a function that receives a path and returns true to skip it, which also prevents descending into excluded directories. Results come back in no particular order, hence the sort() in the example.

Watching for changes

fs.watch(path) asks the operating system to notify you when something under path changes. It is the basis of live-reload servers and node --watch. The promise version is an async iterator of events with eventType ('rename' or 'change') and filename.

The warnings matter more than the API:

  • Behaviour differs between operating systems. Some report a rename as two events, some give filename as null, recursive watching was not supported on Linux in older versions, and network drives often deliver nothing.
  • One save in an editor can fire several events (write temp file, rename, change timestamps). Real tools debounce: they wait a few milliseconds after the last event.
  • Events are hints, not a precise log. After an event, re-read the state instead of trusting the event type.
  • Always provide a way to stop, using an AbortSignal.

Our sandbox cannot show a watcher reliably across platforms, so here is the code you would run on your own machine, labelled read-only:

NODE
// Read-only example: run it on your computer
import { watch } from 'node:fs/promises';

const controller = new AbortController();
setTimeout(() => controller.abort(), 60_000); // stop after a minute

try {
  for await (const event of watch('./src', { recursive: true, signal: controller.signal })) {
    console.log(event.eventType, event.filename);
  }
} catch (error) {
  if (error.name !== 'AbortError') {
    throw error;
  }
}

Cancellation with signals is covered in AbortController and Cancellation. For production file watching with proper debouncing and cross-platform fixes, people use the chokidar library; for simply restarting a script when files change, node --watch does it without any code.

Walking a directory tree

Sometimes you need more control than readdir({ recursive: true }) gives: skip node_modules, stop early, compute sizes, or process one file at a time. An async generator that yields entries is the classic tool. It produces results lazily, so a consumer can break out and the walk stops.

Node.js A recursive walker with an async generator

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.

Notes on this design:

  • Directories are processed one at a time, so memory use stays small. If you want to stat many files in parallel, limit the concurrency (see Concurrency Control and Queues) instead of unleashing Promise.all on 100,000 files, which can hit the EMFILE limit.
  • Using entry.isDirectory() from Dirent does not follow symbolic links, so a link to a parent directory is not entered. That is the safe default.
  • Sorting names makes the output deterministic. Never rely on the order from the operating system.
  • join uses the platform's separator; replaceAll in the demo only keeps the output identical on Windows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does mkdir('a/b/c', { recursive: true }) do when a, a/b and a/b/c already exist?

    With recursive: true existing directories are not an error, which makes it a safe way to ensure a folder exists.
  2. 2. Why use readdir with withFileTypes: true?

    Dirent objects carry the entry type, saving one system call per entry.
  3. 3. What is the difference between stat and lstat on a symbolic link?

    Use lstat when walking trees so that links are recognised and not followed accidentally.
  4. 4. Which call removes a non-empty directory and does not fail if it is already gone?

    recursive removes the contents, force ignores a missing path. Plain rm refuses directories and rmdir only removes empty ones.
  5. 5. Which statement about fs.watch is true?

    fs.watch builds on operating system notifications, which vary. Treat events as hints that something changed.

Summary

  • mkdir(path, { recursive: true }) creates missing parents and tolerates existing folders.
  • readdir returns names in unspecified order; add withFileTypes for Dirent objects and recursive for the whole subtree. Sort when order matters.
  • stat follows links, lstat does not; Stats gives size, times and type methods.
  • rm with recursive and force deletes trees; cp with recursive copies them; rename moves within one file system and replaces existing files.
  • fs.glob (Node 22+) matches patterns like **/*.js as an async iterator.
  • fs.watch is OS dependent: debounce, re-read state, and cancel with an AbortSignal.
  • An async generator makes a lazy, stoppable directory walker; use lstat/Dirent so symbolic links are not followed by accident.

Next: File Streams