Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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:

StudentManagement/
📁 students/
📄 student1.txt
📄 student2.txt
📁 reports/
📄 report.txt
📄 app.js
📄 package.json

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.

app.js
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:

JavaScript
fs.mkdir(path, callback);

Example

app.js
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:

Terminal
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.

Important: If the directory already exists, this example displays an error. To create missing parent directories as well, use the recursive option.

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.

app.js
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:

Project/
📁 data/
📁 students/
📁 records/

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:

JavaScript
fs.readdir(path, callback);

Example

Suppose the project contains the following files:

students/
student1.txt
student2.txt
student3.txt

Now read the directory contents.

app.js
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.

app.js
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.

app.js
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.

app.js
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.

app.js
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.

app.js
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!");
});
Safety warning: Recursive removal can delete all files and subdirectories inside the target folder. Verify the path carefully before using this operation. Do not run deletion code against important project folders.

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.

app.js
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:

Terminal
node app.js

Output:

Student file created successfully!
Files in studentData:
student.txt

Resulting project structure:

Project/
📁 studentData/
📄 student.txt
📄 app.js
📄 package.json

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

  1. Create a project named CourseDirectoryApp.
  2. Create a directory named courses using fs.mkdir().
  3. Create a nested directory named courses/java.
  4. Use the recursive option to create missing directories.
  5. 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

  1. Create a directory named employees.
  2. Add two text files inside it.
  3. Use fs.readdir() to list the entries.
  4. Display each file name in the terminal.
  5. Handle errors if the directory cannot be read.

Expected result: Both file names should appear in the terminal.

Task 3: Rename a Directory

  1. Create an empty directory named oldCourses.
  2. Use fs.rename() to rename it to newCourses.
  3. Handle errors if the operation fails.
  4. 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.