Directories and file information

Topic 3 of 4 in Files & data6 min readIntermediateFree course

Overview

Programs often need to work with whole folders: create a place to save uploads, process every image in a directory, clean out old temporary files, or report what’s taking up disk space. This topic covers the folder side of fs.

Creating folders

JavaScript
import { mkdir } from 'node:fs/promises';

await mkdir('storage/uploads/2026/12', { recursive: true });

recursive: true creates every missing parent folder and doesn’t throw if the folder already exists — so it’s safe to call at start-up every time.

For temporary work, create a uniquely named folder inside the system’s temp directory:

JavaScript
import { mkdtemp } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

const workDir = await mkdtemp(path.join(os.tmpdir(), 'export-'));
// e.g. /tmp/export-a1B2c3

Listing a folder

JavaScript
import { readdir } from 'node:fs/promises';

const names = await readdir('uploads');
// ['avatar.png', 'docs', 'report.pdf']

That gives names only. To know which are files and which are folders, ask for Dirent objects:

JavaScript
const entries = await readdir('uploads', { withFileTypes: true });
for (const entry of entries) {
  console.log(entry.name, entry.isDirectory() ? '📁' : '📄');
}

Filter with ordinary array methods:

JavaScript
const images = (await readdir('photos'))
  .filter((name) => ['.jpg', '.png', '.webp'].includes(path.extname(name).toLowerCase()));

Walking a directory tree

To visit every file in a folder and its sub-folders, write a recursive function:

JavaScript
import { readdir } from 'node:fs/promises';
import path from 'node:path';

async function* walk(dir) {
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      yield* walk(full);
    } else {
      yield full;
    }
  }
}

for await (const file of walk('src')) {
  console.log(file);
}

Using an async generator (from Iterators and generators) means files are produced one at a time, so you can stop early or process millions without building a giant array.

For a quick flat list, readdir can do the recursion itself:

JavaScript
const all = await readdir('src', { recursive: true }); // 'utils/format.js', …

Newer Node versions also include fs.glob for patterns like src/**/*.test.js.

File details with stat

stat tells you about a file or folder without reading its contents:

JavaScript
import { stat } from 'node:fs/promises';

const info = await stat('report.pdf');
info.size;            // bytes
info.isFile();        // true
info.isDirectory();   // false
info.mtime;           // last modified (a Date)
info.birthtime;       // created (where the OS supports it)

A practical use — delete temp files older than a day:

JavaScript
const DAY = 24 * 60 * 60 * 1000;
for (const entry of await readdir(tmp, { withFileTypes: true })) {
  if (!entry.isFile()) continue;
  const file = path.join(tmp, entry.name);
  const { mtimeMs } = await stat(file);
  if (Date.now() - mtimeMs > DAY) await unlink(file);
}

Checking access

access checks whether the current user can read or write a path:

JavaScript
import { access, constants } from 'node:fs/promises';

try {
  await access('storage', constants.W_OK);
} catch {
  throw new Error('The storage folder is not writable — check its permissions');
}

This is useful as a start-up check. For normal operations, don’t check first — just try the read or write and handle the error, because things can change between the check and the action.

Copying and removing folders

JavaScript
import { cp, rm } from 'node:fs/promises';

await cp('templates/starter', 'projects/new-site', { recursive: true });
await rm('dist', { recursive: true, force: true });

Watching for changes

fs.watch calls you when files change — handy for development tools and simple automation:

JavaScript
import { watch } from 'node:fs/promises';

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

try {
  for await (const event of watch('content', { recursive: true, signal: ac.signal })) {
    console.log(event.eventType, event.filename); // 'change' or 'rename'
  }
} catch (err) {
  if (err.name !== 'AbortError') throw err;
}

Watching is notoriously inconsistent between operating systems: you may get several events for one save, 'rename' for creations and deletions, and network drives may not report at all. For production-grade watching, tools such as chokidar smooth over these differences. For restarting your own app during development, node --watch already does the job.

Permissions and ownership

On macOS and Linux, files have permissions for the owner, group and everyone else. You can change them with chmod:

JavaScript
import { chmod } from 'node:fs/promises';
await chmod('secrets.json', 0o600); // owner can read and write; nobody else can

Files containing credentials or keys should never be readable by other users on the machine.

Keep file work out of request paths where you can. Scanning a big folder on every request is slow. Scan once at start-up, cache the result, or move the data into a database.

Exercise

Folder size report

Write folderReport(dir) that walks a folder recursively and returns the number of files, the total size in MB (2 decimal places) and the five largest files with their sizes. Skip node_modules.

JavaScript
import { readdir, stat } from 'node:fs/promises';
import path from 'node:path';

export async function folderReport(dir) {
  // your code here
}

Summary

  • mkdir(dir, { recursive: true }) creates nested folders and doesn’t fail if they exist.
  • readdir with withFileTypes: true tells files and folders apart without extra calls.
  • stat returns size, timestamps and type; access checks permissions.
  • Walk trees recursively, or use readdir(dir, { recursive: true }).
  • fs.watch reacts to changes, but behaves differently across operating systems.