Course contentsShow
← JavaScript
Lesson 1524 of 2,72333. JavaScript in Node.jsFree lesson

Working with Directories: mkdir, readdir, rmdir

Creating, listing contents, and removing directories including recursive options.

Working with Directories: mkdir, readdir, rmdir

You'll learn how to create, list contents, and remove directories programmatically in Node.js.

The Core Idea

Just as you manage files with fs.readFile() and fs.writeFile(), Node.js provides methods to manage directories (folders). You can create new directories with fs.mkdir(), list their contents with fs.readdir(), and remove them with fs.rmdir() or fs.rm().

Think of directories like filing cabinets: you need to create them before storing files, peek inside to see what's there, and eventually empty and remove them when no longer needed.

Creating Directories with mkdir()

const fs = require('fs').promises;

// Create a single directory
await fs.mkdir('./my-folder');

// Create nested directories with recursive option
await fs.mkdir('./parent/child/grandchild', { recursive: true });

The recursive: true option creates all parent directories if they don't exist—like creating a folder path in one go.

Listing Directory Contents with readdir()

// Get array of file/folder names
const items = await fs.readdir('./my-folder');
console.log(items); // ['file1.txt', 'subfolder', 'file2.js']

// Get detailed information about each item
const itemsWithDetails = await fs.readdir('./my-folder', { withFileTypes: true });
itemsWithDetails.forEach(item => {
  console.log(item.name, item.isDirectory() ? '(folder)' : '(file)');
});

Removing Directories with rmdir() and rm()

// Remove empty directory
await fs.rmdir('./empty-folder');

// Remove directory and all its contents recursively
await fs.rm('./my-folder', { recursive: true, force: true });

The recursive: true option deletes everything inside, while force: true ignores errors if the directory doesn't exist.

Key Takeaway: Use fs.mkdir() with recursive: true to create directory paths, fs.readdir() to list contents, and fs.rm() with recursive: true to safely remove directories and their contents.