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

Path Module in Node.js

Learn how to work with file and directory paths using the Node.js path module. Understand path.join(), path.resolve(), path.basename(), path.dirname(), path.extname(), and other useful path methods through practical programs and outputs.

1. What Is the Path Module?

The path module is a built-in Node.js module used to work with file and directory paths. It provides methods for joining path segments, resolving paths, extracting filenames, finding directory names, and identifying file extensions.

For example, suppose our application needs to work with a file named student.txt inside a folder named students. Instead of manually joining folder and filename strings, we can use the path module.

Example

JavaScript
const path = require("node:path");

const filePath = path.join("students", "student.txt");

console.log(filePath);

Output on Windows

Output
students\student.txt

Explanation: The require("node:path") statement loads the built-in path module. The path.join() method joins the folder name and filename using the appropriate path separator for the operating system.

Definition: The path module provides utilities for creating, combining, resolving, and examining file and directory paths in Node.js.

2. Why Do We Use the Path Module?

Applications often need to locate files, read filenames, identify extensions, or build paths dynamically. The path module provides methods for these tasks.

  • Join Paths: Combine folder names and filenames.
  • Resolve Paths: Convert path segments into an absolute path.
  • Extract Filenames: Get the filename from a complete path.
  • Find Directory Names: Get the directory portion of a path.
  • Find Extensions: Identify extensions such as .js, .txt, and .json.
  • Cross-platform Support: Use platform-appropriate path separators when constructing paths.

3. How the Path Module Works

We provide path information to a method from the path module. The method processes the path and returns a result that our application can use.

Step 1: Input Path

Folder: students
Filename: student.txt

↓
Step 2: Path Method

Use path.join() to combine the path segments.

↓
Step 3: Processed Path

The path module creates a combined path.

↓
Step 4: Use the Result

Store the path or use it in file operations.

4. Importing the Path Module

Since path is a built-in Node.js module, we do not need to install a separate package to use it.

Example

JavaScript - app.js
const path = require("node:path");

console.log("Path module loaded successfully.");

Output

Output
Path module loaded successfully.

Explanation: The variable path refers to the module's exported methods. We can access those methods using dot notation, such as path.join() and path.basename().

5. Understanding path.join()

The path.join() method combines multiple path segments into a single normalized path. It handles the appropriate path separator for the current operating system.

Example

JavaScript - app.js
const path = require("node:path");

const filePath = path.join(
    "students",
    "details",
    "student.txt"
);

console.log(filePath);

Output on Windows

Output
students\details\student.txt

Output on POSIX Systems

Output
students/details/student.txt

Explanation: The method combines three segments: students, details, and student.txt. The result is a single path. The actual separator depends on the operating system running the program.

6. Understanding path.resolve()

The path.resolve() method converts a sequence of path segments into an absolute path. An absolute path identifies a location starting from the file system root or the appropriate drive root.

Example

JavaScript - app.js
const path = require("node:path");

const absolutePath = path.resolve("students", "student.txt");

console.log(absolutePath);

Example Output

Output - Illustrative Windows Example
C:\Projects\MyApp\students\student.txt

Explanation: The actual output depends on the current working directory and operating system. The displayed path is only an example. path.resolve() uses the current working directory when a fully absolute path has not been provided.

Remember: path.join() combines path segments, whereas path.resolve() calculates an absolute path. They serve different purposes.

7. Understanding path.basename()

The path.basename() method returns the final portion of a path, usually the filename.

Example

JavaScript - app.js
const path = require("node:path");

const filePath = path.join(
    "students",
    "details",
    "student.txt"
);

console.log(path.basename(filePath));

Output

Output
student.txt

Explanation: The full path contains folder names and a filename. path.basename() returns only the final path component, which is student.txt in this example.

Example: Remove the Extension

JavaScript
const path = require("node:path");

console.log(path.basename("students/student.txt", ".txt"));

Output

Output
student

The second argument tells path.basename() which ending to remove when it matches the end of the basename.

8. Understanding path.dirname()

The path.dirname() method returns the directory portion of a path. It removes the final path component and returns the remaining directory path.

Example

JavaScript - app.js
const path = require("node:path");

const filePath = path.join(
    "students",
    "details",
    "student.txt"
);

console.log(path.dirname(filePath));

Output on Windows

Output
students\details

Explanation: The last component is student.txt. The dirname() method returns the directory containing that file, which is students\details on Windows.

9. Understanding path.extname()

The path.extname() method returns the extension of the final component of a path. The extension includes the leading dot when one is present.

Example

JavaScript - app.js
const path = require("node:path");

console.log(path.extname("app.js"));
console.log(path.extname("student.txt"));
console.log(path.extname("data.json"));

Output

Output
.js
.txt
.json

Explanation: The method examines the final component of each path and returns its extension. If the filename has no extension, the method returns an empty string.

Example Without an Extension

JavaScript
const path = require("node:path");

console.log(path.extname("README"));

Output

Output

No visible characters are printed because the returned extension is an empty string.

10. Understanding path.parse()

The path.parse() method breaks a path into separate parts and returns an object containing properties such as root, directory, base, extension, and name.

Example

JavaScript - app.js
const path = require("node:path");

const fileInfo = path.parse("students/student.txt");

console.log("Base:", fileInfo.base);
console.log("Name:", fileInfo.name);
console.log("Extension:", fileInfo.ext);

Output

Output
Base: student.txt
Name: student
Extension: .txt

Explanation: The parse() method returns an object. The base property contains the filename with its extension, name contains the filename without the extension, and ext contains the extension.

11. Comparing Common Path Methods

Method Purpose Example Result
path.join() Combines path segments. students/student.txt on POSIX
path.resolve() Creates an absolute path. Depends on the working directory.
path.basename() Returns the final path component. student.txt
path.dirname() Returns the directory portion. students
path.extname() Returns the filename extension. .txt
path.parse() Breaks a path into components. An object containing path parts.

12. Understanding a File Path

Consider the path students/details/student.txt. Different path methods help us extract different information from this same path.

Complete Path

students/details/student.txt

↓
Directory

path.dirname()

Result: students/details

Filename

path.basename()

Result: student.txt

Extension

path.extname()

Result: .txt

Parsed Information

path.parse() returns an object containing the path components.

13. Practical Program: Analyze a File Path

Let us combine several path methods in one program. This program accepts a path and displays its filename, directory, extension, and parsed filename information.

Complete Program

JavaScript - app.js
const path = require("node:path");

const filePath = path.join(
    "students",
    "details",
    "student.txt"
);

const fileName = path.basename(filePath);
const directoryName = path.dirname(filePath);
const extension = path.extname(filePath);
const fileInfo = path.parse(filePath);

console.log("Complete Path:", filePath);
console.log("Directory:", directoryName);
console.log("Filename:", fileName);
console.log("Extension:", extension);
console.log("Name Without Extension:", fileInfo.name);

Output on Windows

Output
Complete Path: students\details\student.txt
Directory: students\details
Filename: student.txt
Extension: .txt
Name Without Extension: student

Detailed Explanation:

  • path.join() combines the folder and filename segments.
  • path.basename() extracts student.txt.
  • path.dirname() returns the directory portion.
  • path.extname() extracts the .txt extension.
  • path.parse() returns an object from which we access the filename without its extension through fileInfo.name.

14. Common Mistakes

Mistake Correct Approach
Manually joining path strings with separators. Use path.join() for path construction.
Assuming path.join() always returns an absolute path. Use path.resolve() when an absolute path is required.
Confusing the filename with the directory. Use basename() for the final component and dirname() for the directory portion.
Assuming every system uses the same path separator. Remember that path formatting depends on the operating system.
Assuming extname() always returns an extension. It returns an empty string when no extension is present.

15. Practice Tasks

Task 1: Join a File Path

Use path.join() to combine the folders courses and nodejs with the filename notes.txt.

Expected Path on Windows: courses\nodejs\notes.txt

Task 2: Extract Filename and Extension

Use path.basename() and path.extname() to display the filename and extension from reports/marks.json.

Expected Output: marks.json and .json

Task 3: Analyze a File Path

Create a path for students/results/final.txt. Display the directory name, filename, extension, and filename without the extension.

Challenge: Add path.resolve() to your program and observe how the output changes when you run it from a different working directory.

Important Points

  • The path module is built into Node.js.
  • path.join() combines path segments.
  • path.resolve() creates an absolute path.
  • path.basename() returns the final path component.
  • path.dirname() returns the directory portion.
  • path.extname() returns the file extension.
  • path.parse() returns an object containing separate path components.
  • The default path behavior depends on the operating system. Node.js also provides path.posix and path.win32 for explicitly working with POSIX or Windows path formats.

Summary

The Node.js path module provides methods for working with file and directory paths. The path.join() method combines path segments, while path.resolve() creates an absolute path. The path.basename() method extracts the final path component, path.dirname() returns the directory portion, path.extname() identifies the file extension, and path.parse() separates a path into useful components. These methods help developers build reliable, organized, and cross-platform Node.js applications without manually handling path separators.