typescriptbeginner

Directory Operations with fs

Create, read, copy, and remove directories recursively using Node.js fs/promises.

typescript
import {
  mkdir, readdir, stat, rm, cp, rename,
  writeFile
} from 'fs/promises';
import path from 'path';

// Create directory (recursive)
async function ensureDir(dirPath: string): Promise<void> {
  await mkdir(dirPath, { recursive: true });
}

// List directory contents with details
async function listDir(dirPath: string) {
  const entries = await readdir(dirPath, { withFileTypes: true });

  return entries.map((entry) => ({
    name: entry.name,
    type: entry.isDirectory() ? 'dir' : 'file',
    path: path.join(dirPath, entry.name),
  }));
}

// Recursive directory listing (walk)
async function walk(dir: string): Promise<string[]> {
  const files: string[] = [];
  const entries = await readdir(dir, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      files.push(...(await walk(fullPath)));
    } else {
      files.push(fullPath);
    }
  }
  return files;
}

// Directory size
async function dirSize(dir: string): Promise<number> {
  const files = await walk(dir);
  let total = 0;
  for (const file of files) {
    const stats = await stat(file);
    total += stats.size;
  }
  return total;
}

// Find files by extension
async function findByExtension(dir: string, ext: string): Promise<string[]> {
  const allFiles = await walk(dir);
  return allFiles.filter((f) => path.extname(f) === ext);
}

// Copy directory
async function copyDir(src: string, dest: string): Promise<void> {
  await cp(src, dest, { recursive: true });
}

// Remove directory
async function removeDir(dir: string): Promise<void> {
  await rm(dir, { recursive: true, force: true });
}

// Usage
const testDir = path.join(process.cwd(), 'test-dir');

// Create structure
await ensureDir(path.join(testDir, 'src', 'utils'));
await ensureDir(path.join(testDir, 'dist'));
await writeFile(path.join(testDir, 'src', 'index.ts'), 'console.log("hi")');
await writeFile(path.join(testDir, 'src', 'utils', 'helpers.ts'), 'export {}');

// List
const entries = await listDir(testDir);
console.log('Contents:', entries);

// Walk
const allFiles = await walk(testDir);
console.log('All files:', allFiles);

// Find .ts files
const tsFiles = await findByExtension(testDir, '.ts');
console.log('.ts files:', tsFiles);

// Size
const size = await dirSize(testDir);
console.log('Size:', size, 'bytes');

// Cleanup
await removeDir(testDir);
console.log('Cleaned up');

Use Cases

  • Build tool directory management
  • File system scaffolding
  • Recursive file operations

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.