Directories and file information
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
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:
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-a1B2c3Listing a folder
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:
const entries = await readdir('uploads', { withFileTypes: true });
for (const entry of entries) {
console.log(entry.name, entry.isDirectory() ? '📁' : '📄');
}Filter with ordinary array methods:
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:
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:
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:
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:
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:
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
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:
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:
import { chmod } from 'node:fs/promises';
await chmod('secrets.json', 0o600); // owner can read and write; nobody else canFiles 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.
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.
import { readdir, stat } from 'node:fs/promises';
import path from 'node:path';
export async function folderReport(dir) {
// your code here
}import { readdir, stat } from 'node:fs/promises';
import path from 'node:path';
export async function folderReport(dir) {
const files = [];
async function walk(current) {
for (const entry of await readdir(current, { withFileTypes: true })) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) {
if (entry.name !== 'node_modules') await walk(full);
} else if (entry.isFile()) {
files.push({ file: full, size: (await stat(full)).size });
}
}
}
await walk(dir);
const total = files.reduce((sum, f) => sum + f.size, 0);
return {
count: files.length,
totalMB: (total / 1024 ** 2).toFixed(2),
largest: files.toSorted((a, b) => b.size - a.size).slice(0, 5),
};
}Summary
mkdir(dir, { recursive: true })creates nested folders and doesn’t fail if they exist.readdirwithwithFileTypes: truetells files and folders apart without extra calls.statreturns size, timestamps and type;accesschecks permissions.- Walk trees recursively, or use
readdir(dir, { recursive: true }). fs.watchreacts to changes, but behaves differently across operating systems.