Node JS Tutorial - Creating & Removing Directories

In this tutorial, we will learn about creating and removing directories using the Node.js fs core module. This module provides many handy methods that allow us to create, delete, and check if a directory exists.

Creating a Directory

First, let's see how we can create a directory using the fs mkdir method. Go to the index.js file and write the following code:


const fs = require('fs');
const dir= '/users';

fs.exists('data.js',function(exists){
if(!exists)
{
fs.mkdirSync(dir)
}
else
{
console.log("Directory already exists.");
}
});

Now, let's check. Go to the command prompt and run the command:


node index.js

Okay, the directory has been created. Let's check by switching to the project, and you can see the "users" directory.

If you run the index.js file again, you will see a message indicating that the directory already exists.

Renaming a Directory

Now, let's see how we can rename a directory. Go to the index.js file and write the following code:


const fs = require('fs');
fs.rename('/Users', '/Admins', err => {
if (err) {
console.error(err)
return.
}
});

Switch to the command prompt and run the command:


node index.js

The folder has been renamed. Let's check by switching to the project, and you can see that the "Users" folder has been renamed to "Admin".

Removing a Directory

Now, let's see how we can remove a directory. To do this, write the following code:


fs.rmdir('Admins',function(deleted){
    console .log('Directroy has been deleted successfully!.');
});

Let's check. Go to the command prompt and re-run the index.js file. You will see that the directory has been deleted.

In this way, you can create, rename, and delete directories in Node.js, giving you control over your file system.