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.
Creating and removing directories in 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.
myFolder in the current location.await mkdir('myFolder');
parent and inside it child folder, even if parent does not exist yet.await mkdir('parent/child', { recursive: true });
myFolder if it is empty.await rmdir('myFolder');
This program creates a folder called testDir and then removes it. It prints messages to show what it did.
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();
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.
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.