Working with Directories in Node.js
A directory is a folder used to organize files and other folders. Node.js provides File System methods that allow us to create, read, rename, and remove directories programmatically.
For example, a student management application can create separate folders for student records, reports, and temporary files. The Node.js File System module helps us manage these folders using JavaScript.
1. What Is a Directory?
A directory is another name for a folder. It helps organize files in a structured way. A directory can contain files and other directories called subdirectories.
For example, a Node.js project may have the following structure:
Here, students and reports are
directories. The text files are stored inside those directories,
while app.js contains the application code.
2. Import the File System Module
Node.js provides a built-in module called fs.
We can use it to perform directory operations without installing
an additional NPM package.
const fs = require("fs");
console.log("File System module loaded successfully!");
Output:
File System module loaded successfully!
The require("fs") statement imports the module
and stores its exported methods in the fs variable.
3. Create a Directory Using fs.mkdir()
The fs.mkdir() method creates a new directory.
It is commonly used when an application needs to organize
files into separate folders.
Syntax:
fs.mkdir(path, callback);
Example
const fs = require("fs");
fs.mkdir("students", (err) => {
if (err) {
console.log("Error creating directory:", err.message);
return;
}
console.log("Students directory created successfully!");
});
Run the program:
node app.js
Output when the directory is created successfully:
Students directory created successfully!
A new folder named students is created in the
current working directory.
4. Create Nested Directories
Sometimes, we need to create a directory inside another directory. This is called creating nested directories.
The recursive: true option allows Node.js to
create missing parent directories.
const fs = require("fs");
fs.mkdir("data/students/records", { recursive: true }, (err) => {
if (err) {
console.log("Error creating directories:", err.message);
return;
}
console.log("Nested directories created successfully!");
});
Output:
Nested directories created successfully!
Created structure:
If the requested directory already exists, recursive creation normally completes without an error.
5. Read Directory Contents Using fs.readdir()
The fs.readdir() method reads the contents of a
directory. It returns the names of files and subdirectories
inside the specified directory.
Syntax:
fs.readdir(path, callback);
Example
Suppose the project contains the following files:
Now read the directory contents.
const fs = require("fs");
fs.readdir("students", (err, files) => {
if (err) {
console.log("Error reading directory:", err.message);
return;
}
console.log("Directory contents:");
files.forEach((file) => {
console.log(file);
});
});
Example output:
Directory contents:
student1.txt
student2.txt
student3.txt
The exact order of directory entries is not guaranteed. The returned array contains entry names, including names of subdirectories.
6. Identify Files and Directories
By default, fs.readdir() returns names. If we
also need to identify which entries are files and which are
directories, we can use the withFileTypes option.
const fs = require("fs");
fs.readdir("students", { withFileTypes: true }, (err, entries) => {
if (err) {
console.log("Error reading directory:", err.message);
return;
}
entries.forEach((entry) => {
if (entry.isDirectory()) {
console.log("Directory:", entry.name);
} else if (entry.isFile()) {
console.log("File:", entry.name);
}
});
});
Example output:
File: student1.txt
File: student2.txt
Directory: archived
The output depends on the actual contents of the
students directory. Each entry is a
Dirent object, which provides methods such as
isFile() and isDirectory().
7. Check Whether a Directory Exists
We can use fs.stat() to get information about a
path and check whether it points to a directory.
const fs = require("fs");
fs.stat("students", (err, stats) => {
if (err) {
console.log("Directory does not exist or cannot be accessed.");
return;
}
if (stats.isDirectory()) {
console.log("The path is a directory.");
} else {
console.log("The path is not a directory.");
}
});
Output when students is a directory:
The path is a directory.
The stats.isDirectory() method checks whether the
path refers to a directory. If the path cannot be accessed,
the error is handled first.
8. Rename a Directory Using fs.rename()
The fs.rename() method can rename a directory
or move it to another location, subject to file-system rules
and permissions.
For this example, make sure a directory named
oldStudents exists and
newStudents does not already exist.
const fs = require("fs");
fs.rename("oldStudents", "newStudents", (err) => {
if (err) {
console.log("Error renaming directory:", err.message);
return;
}
console.log("Directory renamed successfully!");
});
Output:
Directory renamed successfully!
The directory name changes from oldStudents to
newStudents. The files inside the directory
remain there.
9. Remove an Empty Directory
The fs.rmdir() method can remove an empty
directory. The directory must exist, and it must be empty
for this basic example.
Create an empty directory named oldFolder
before running the following program.
const fs = require("fs");
fs.rmdir("oldFolder", (err) => {
if (err) {
console.log("Error removing directory:", err.message);
return;
}
console.log("Empty directory removed successfully!");
});
Output:
Empty directory removed successfully!
The directory is removed only if the operation succeeds. If the directory contains files, this basic call will fail.
Removing a Directory with fs.rm()
Modern Node.js also provides fs.rm(), which
supports removing directories recursively when that behaviour
is explicitly requested.
const fs = require("fs");
fs.rm("oldFolder", { recursive: true }, (err) => {
if (err) {
console.log("Error removing folder:", err.message);
return;
}
console.log("Directory removed successfully!");
});
10. Complete Practical Example
Let's create a directory, write a file inside it, and list its contents. This example combines directory and file operations into one workflow.
const fs = require("fs");
fs.mkdir("studentData", { recursive: true }, (mkdirErr) => {
if (mkdirErr) {
console.log("Error creating directory:", mkdirErr.message);
return;
}
fs.writeFile(
"studentData/student.txt",
"Student Name: Rahul\nCourse: Node.js",
(writeErr) => {
if (writeErr) {
console.log("Error writing file:", writeErr.message);
return;
}
console.log("Student file created successfully!");
fs.readdir("studentData", (readErr, files) => {
if (readErr) {
console.log("Error listing directory:", readErr.message);
return;
}
console.log("Files in studentData:");
files.forEach((file) => {
console.log(file);
});
});
}
);
});
Run the program:
node app.js
Output:
Student file created successfully!
Files in studentData:
student.txt
Resulting project structure:
The program creates the directory, writes student information
to a file inside it, and then displays the file name using
fs.readdir().
11. Common Directory Methods
| Method | Purpose |
|---|---|
fs.mkdir() |
Creates a directory. |
fs.readdir() |
Reads directory entries. |
fs.stat() |
Gets information about a file-system path. |
fs.rename() |
Renames or moves a file or directory. |
fs.rmdir() |
Removes an empty directory. |
fs.rm() |
Removes files or directories, with options for recursive removal. |
12. Practice Tasks
Task 1: Create a Course Directory
- Create a project named
CourseDirectoryApp. - Create a directory named
coursesusingfs.mkdir(). - Create a nested directory named
courses/java. - Use the recursive option to create missing directories.
- Display a success message after the operation.
Expected result: The project should contain
a courses folder and a nested java
folder.
Task 2: List Files in a Directory
- Create a directory named
employees. - Add two text files inside it.
- Use
fs.readdir()to list the entries. - Display each file name in the terminal.
- Handle errors if the directory cannot be read.
Expected result: Both file names should appear in the terminal.
Task 3: Rename a Directory
- Create an empty directory named
oldCourses. - Use
fs.rename()to rename it tonewCourses. - Handle errors if the operation fails.
- Verify the new directory name in your project.
Expected result: The directory name should
change to newCourses.
Summary
Working with directories in Node.js allows applications
to organize files and folders programmatically. The
fs.mkdir() method creates directories,
fs.readdir() lists their contents,
fs.stat() provides path information, and
fs.rename() renames or moves directories.
Directory removal can be performed using suitable methods
such as fs.rmdir() for empty directories and
fs.rm() when its options match the requirement.
In this lesson, we created nested directories, listed files, identified file-system entries, renamed directories, and combined file and directory operations in a practical example. These concepts help developers organize application data and manage project files in Node.js at CIIT Training Institute.