Whenever we work with files and folders in Node.js, we often need to build file paths, extract file names, find extensions, or navigate directories.
Imagine you're building an application that:
- Uploads images
- Reads configuration files
- Saves reports
- Creates log files
- Serves static assets
In all these cases, you'll work with file paths.
Instead of manually concatenating strings like this:
const filePath = "users/" + "images/" + "profile.png";
Node.js provides a built-in Path module that handles paths correctly across different operating systems.
In this article, we'll learn the most commonly used methods of the Path module with step-by-step examples.
Let's get started!
What is the Path Module?
The Path module is a built-in Node.js module that provides utilities for working with file and directory paths.
It helps developers:
- Join paths
- Resolve absolute paths
- Extract file names
- Get file extensions
- Parse file paths
- Normalize paths
- Check absolute paths
The biggest advantage is that it works correctly on both Windows and macOS/Linux without you worrying about different path separators.
Since it's a built-in module, you don't need to install anything.
Simply import it.
const path = require("path");
Or if you're using ES Modules:
import path from "node:path";
Why Do We Need the Path Module?
Different operating systems use different path separators.
Windows uses:
C:\Users\John\Documents
Linux and macOS use:
/Users/john/Documents
If you manually build paths using string concatenation, your application may work on one operating system but fail on another.
The Path module automatically handles these differences.
Understanding path.join()
What is path.join()?
path.join() combines multiple path segments into a single path.
It also removes duplicate slashes and uses the correct path separator for the operating system.
Step 1: Create a File
Create:
join.js
Add the following code:
const path = require("path");
const filePath = path.join("users", "images", "profile.png");
console.log(filePath);
Run:
node join.js
Output on Windows:
users\images\profile.png
Output on macOS/Linux:
users/images/profile.png
Explanation
Instead of manually adding / or \, let the Path module handle it for you.
Real-World Example
Suppose you're saving uploaded images.
const uploadPath = path.join("uploads", "users", "avatar.png");
console.log(uploadPath);
Output:
uploads/users/avatar.png
(or uploads\users\avatar.png on Windows)
Understanding path.resolve()
What is path.resolve()?
path.resolve() converts a relative path into an absolute path.
const path = require("path");
console.log(path.resolve("images"));
Output:
C:\Projects\my-app\images
or
/Users/john/my-app/images
depending on your operating system.
Difference Between join() and resolve()
Suppose your current directory is:
C:\Projects\my-app
path.join()
path.join("images", "logo.png");
Output:
images/logo.png
path.resolve()
path.resolve("images", "logo.png");
Output:
C:\Projects\my-app\images\logo.png
Summary
join()→ Creates a relative path.resolve()→ Returns an absolute path.
Understanding path.basename()
What is path.basename()?
Returns the last portion of a path (usually the file name).
const path = require("path");
const file = path.basename("/users/images/profile.png");
console.log(file);
Output:
profile.png
Remove the Extension
const file = path.basename("/users/images/profile.png", ".png");
console.log(file);
Output:
profile
Understanding path.dirname()
Returns the directory portion of a path.
const path = require("path");
console.log(path.dirname("/users/images/profile.png"));
Output:
/users/images
Understanding path.extname()
Returns the extension of a file.
const path = require("path");
console.log(path.extname("profile.png"));
Output:
.png
Another example:
console.log(path.extname("document.pdf"));
Output:
.pdf
Real-World Use Case
Check whether a user uploads an image.
const extension = path.extname("photo.jpg");
if (extension === ".jpg") {
console.log("Image uploaded");
}
Understanding path.parse()
path.parse() converts a path into an object.
const path = require("path");
console.log(path.parse("/users/images/profile.png"));
Output:
{
root: "/",
dir: "/users/images",
base: "profile.png",
ext: ".png",
name: "profile"
}
Explanation
root i.e, Root directory
dir i.e, Folder path
base i.e, File name with extension
ext i.e, File extension
name i.e, File name without extension
Understanding path.format()
path.format() does the opposite of path.parse().
It converts an object back into a file path.
const path = require("path");
const file = path.format({
dir: "/users/images",
name: "profile",
ext: ".png",
});
console.log(file);
Output:
/users/images/profile.png
Understanding path.normalize()
Sometimes paths contain unnecessary slashes.
const path = require("path");
console.log(path.normalize("/users//images///profile.png"));
Output:
/users/images/profile.png
It removes duplicate separators and normalizes the path.
Understanding path.isAbsolute()
Checks whether a path is absolute.
const path = require("path");
console.log(path.isAbsolute("/users/images"));
Output:
true
Example:
console.log(path.isAbsolute("images/profile.png"));
Output:
false
Understanding path.relative()
Returns the relative path between two locations.
const path = require("path");
const result = path.relative("/users/images", "/users/videos");
console.log(result);
Output:
../videos
Understanding __dirname
Although it's not part of the Path module, developers often use it together with Path.
console.log(__dirname);
Output:
C:\Projects\Node-App
Combine it with path.join().
const path = require("path");
const file = path.join(__dirname, "uploads", "image.png");
console.log(file);
Output:
C:\Projects\Node-App\uploads\image.png
This is one of the most common patterns in Node.js applications.
Build a Simple File Path Utility
Create:
app.js
const path = require("path");
console.log("File Name:", path.basename(__filename));
console.log("Directory:", path.dirname(__filename));
console.log("Extension:", path.extname(__filename));
console.log("Current Folder:", __dirname);
console.log(
"Uploads Folder:",
path.join(__dirname, "uploads", "profile.png")
);
console.log(
"Absolute Path:",
path.resolve("uploads", "profile.png")
);
Run:
node app.js
Example Output:
File Name: app.js
Directory: C:\Projects\Node-App
Extension: .js
Current Folder: C:\Projects\Node-App
Uploads Folder: C:\Projects\Node-App\uploads\profile.png
Absolute Path: C:\Projects\Node-App\uploads\profile.png
Comparison of Common Path Methods
join() - Joins multiple path segments
resolve() - Returns an absolute path
basename() - Returns the file name
dirname() - Returns the directory path
extname() - Returns the file extension
parse() - Converts a path into an object
format() - Converts an object into a path
normalize() - Removes unnecessary separators
relative() - Returns the relative path between two paths
isAbsolute() - Checks whether a path is absolute
Best Practices
When working with the Path module:
- Always use
path.join()instead of manually concatenating file paths. - Use
path.resolve()when you need an absolute path. - Combine
__dirnamewithpath.join()to locate project files reliably. - Validate uploaded file extensions using
path.extname(). - Avoid hardcoding Windows (
\) or Linux (/) path separators.
Common Beginner Mistakes
Here are some mistakes developers often make:
- Building paths using string concatenation.
- Hardcoding
/or\as path separators. - Confusing
join()withresolve(). - Assuming file extensions always exist.
- Forgetting that
__dirnamerefers to the current file's directory.
Final Thoughts
The Path module is one of the most frequently used built-in modules in Node.js. Whether you're reading files, uploading images, serving static assets, or managing project directories, you'll use it regularly.
In this article, you learned:
- What the Path module is
- Why it's important
- How to use
join() - How to use
resolve() - How to extract file names and extensions
- How to parse and format paths
- How to normalize paths
- How to work with absolute and relative paths
- How to combine
__dirnamewith the Path module
Mastering the Path module will help you write cleaner, more portable, and cross-platform Node.js applications.
Happy Coding! 🚀