Node.js

Create nested directories in Node.js

Use mkdir with recursive true when a script needs a directory tree that might not exist yet. Await creation before writing a file inside the final directory.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
  const nested = join(directory, "reports", "daily");
  await fs.mkdir(nested, {recursive: true});
  await fs.writeFile(join(nested, "report.txt"), "ready", "utf8");
  console.log((await fs.stat(nested)).isDirectory());
} finally {
  await fs.rm(directory, {recursive: true, force: true});
}

How it works

Recursive creation handles missing parent directories. It also permits an existing directory at the requested path, making repeated setup straightforward. The example then writes one small report to show the ordering dependency between setup and use.

Limits and mistakes

An existing file with the same path still causes a conflict. Recursive creation does not validate whether an untrusted path is inside an allowed directory. Apply path and permission policies separately when callers control filenames.

Check the result

Expect true. Run mkdir twice against the same nested directory in a temporary fixture, then test a conflicting file path to confirm that real conflicts remain visible.

Sources

Reference documentation for the behavior used in this guide: