0
0
Node.jsframework~5 mins

Creating and removing directories in Node.js

Choose your learning style9 modes available
Introduction

We create directories to organize files and remove them when they are no longer needed. This helps keep your computer tidy and your projects organized.

When you want to save files in a new folder for a project.
When you need to clean up temporary folders after a task is done.
When your program needs to prepare a place to store user uploads.
When you want to delete old folders that are empty or no longer useful.
Syntax
Node.js
import { mkdir, rmdir } from 'node:fs/promises';

// Create a directory
await mkdir(path, { recursive: true });

// Remove a directory
await rmdir(path);

mkdir creates a new directory. The recursive: true option lets you create nested folders at once.

rmdir removes an empty directory. It will fail if the directory has files inside.

Examples
This creates a folder named myFolder in the current location.
Node.js
await mkdir('myFolder');
This creates parent and inside it child folder, even if parent does not exist yet.
Node.js
await mkdir('parent/child', { recursive: true });
This removes the folder named myFolder if it is empty.
Node.js
await rmdir('myFolder');
Sample Program

This program creates a folder called testDir and then removes it. It prints messages to show what it did.

Node.js
import { mkdir, rmdir } from 'node:fs/promises';

async function manageDirectories() {
  const folder = 'testDir';

  // Create a directory
  await mkdir(folder, { recursive: true });
  console.log(`Created directory: ${folder}`);

  // Remove the directory
  await rmdir(folder);
  console.log(`Removed directory: ${folder}`);
}

manageDirectories();
OutputSuccess
Important Notes

Trying to remove a directory that has files will cause an error. You must delete files first or use other methods.

Using recursive: true with mkdir helps create nested folders easily.

Always handle errors in real programs to avoid crashes when folders exist or don't exist.

Summary

Use mkdir to create folders and rmdir to remove empty folders.

The recursive option lets you create nested folders in one step.

Removing folders only works if they are empty; otherwise, delete files first.