Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
What are modules in Node JS ?
Next article icon

Node.js Path Module

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The path module in Node.js is a core module that offers utilities for managing file and directory paths. It helps handle and transform paths across different operating systems, ensuring platform independence. The module includes methods for joining, resolving, and normalizing paths, among other common file system tasks.

Path Module in Node.js

The path module simplifies the management of file paths in Node.js applications, making it easier to navigate the file system regardless of the operating system. It takes away the differences in path formats, such as the use of forward slashes (/) in Unix-based systems and backslashes (\) in Windows.

This module is important for any Node.js developer who needs to manipulate or work with file paths, ensuring that your code is both portable and reliable.

Installation Step (Optional)

Installation is an optional step as the path module is a built-in module in Node.js. Install the assert module using the following command:

npm install path

Importing the Module

To start using the path module in your Node.js application, import it as follows:

const path = require('path');

Explore this Path Module Complete Reference to find detailed explanations, advanced examples, and expert tips for mastering its features to improve your Node.js development.

Path Methods

Method

Description

path.join()

Joins multiple path segments into a single path.

path.resolve()

Resolves a sequence of paths into an absolute path.

path.normalize()

Normalizes a path by resolving .. and . segments.

path.isAbsolute()

Returns true if the path is an absolute path.

path.basename()

Returns the last portion of a path, typically the file name.

path.dirname()

Returns the directory name of a path.

path.extname()

Returns the extension of the file in a path.

path.parse()

Parses a path into an object with properties like root, dir, base, etc.

path.format()

Returns a path string from an object created by path.parse().

path.relative()

Computes the relative path from one absolute path to another.

path.sep

Provides the platform-specific path segment separator (/ on POSIX, \ on Windows).

path.delimiter

Provides the platform-specific path delimiter (: on POSIX, ; on Windows).

Features of Path Module

  • Cross-Platform Path Handling : The path module allows you to work with file paths in a platform-independent manner, ensuring consistent behavior across different operating systems.
  • Path Resolution and Normalization : It provides methods to resolve absolute paths, normalize paths, and remove redundant path segments, which simplifies file path management.
  • Path Parsing and Formatting : The module includes functions for extracting and formatting path components such as directory names, file names, and extensions.
  • Convenient Path Operations : Functions like path.join() and path.resolve() make it easy to concatenate and resolve paths, reducing the likelihood of errors.

Example 1: This example shows how to use path.extname() to get the file extension from a file path. This is helpful for tasks like filtering files by their type.

JavaScript
console.clear();
const path = require('path');

// Define a file path
const filePath = '/users/gfg/documents/report.pdf';

// Extract the file extension
const fileExtension = path.extname(filePath);

console.log(`File Extension: ${fileExtension}`);

Output

File Extension: .pdf

Example 2: This example shows how to use the path.resolve() method to resolve a sequence of paths or path segments into an absolute path.

JavaScript
console.clear();
const path = require('path');
// Resolving an absolute path from segments
const absolutePath = path.resolve('users', 'gfg', 'documents');
console.log(absolutePath);

Output

/your/current/directory/users/gfg/documents

Benefits of Path Module

  • Cross-Platform Compatibility: The path module abstracts the differences between file path formats on various operating systems, allowing you to write code that runs consistently on different platforms.
  • Simplified File Operations: By offering a set of easy-to-use methods, the path module simplifies complex file path operations, reducing the potential for errors.
  • Built-In and Ready to Use: As a core Node.js module, path requires no external dependencies, ensuring that you can start using it immediately without additional setup.
  • Improved Code Readability: Using path methods makes your code cleaner and easier to understand, as it reduces the need for manual string manipulation.
  • Enhanced Reliability: The path module handles edge cases and anomalies in file paths, leading to more robust and error-free code.

Summary

The path module in Node.js is a powerful tool for managing and manipulating file paths in a cross-platform manner. By providing a variety of methods for joining, resolving, and parsing paths, it ensures that your Node.js applications can handle file operations consistently and efficiently, regardless of the operating system. Whether you're working with simple file paths or complex directory structures, the path module is an indispensable part of the Node.js ecosystem.

Recent Articles on Node.js Path Module:

  • Node.js path.basename() Method
  • Node.js path.dirname() Method
  • Node.js path.extname() Method
  • Node.js path.format() Method
  • Node.js path.isAbsolute() Method
  • Node.js path.join() Method
  • Node.js path.normalize() Method
  • Node.js path.parse() Method
  • Node.js path.relative() Method
  • Node path.resolve() Method
  • Node.js path.toNamespacedPath() Method
  • Node.js path.delimiter Property

Next Article
What are modules in Node JS ?

A

abhaykjyo2
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • module

Similar Reads

    Node.js VM Module
    The VM (Virtual Machine) module in Node.js lets you safely run JavaScript code in a separate, isolated environment. This feature is especially handy when you need to execute code without affecting the rest of your application, making it ideal for handling untrusted code or creating distinct executio
    4 min read
    Node.js Utility Module
    The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes. Node.js Utility ModuleThe util module offers essential utilities that are n
    4 min read
    Node.js Utility Module
    The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes. Node.js Utility ModuleThe util module offers essential utilities that are n
    4 min read
    Node.js Utility Module
    The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes. Node.js Utility ModuleThe util module offers essential utilities that are n
    4 min read
    What are modules in Node JS ?
    In NodeJS, modules are encapsulated units of code that can be reused across different parts of an application. Modules help organize code into smaller, manageable pieces, promote code reusability, and facilitate better maintainability and scalability of NodeJS applications. Types of Modules:Core Mod
    2 min read
    What are modules in Node JS ?
    In NodeJS, modules are encapsulated units of code that can be reused across different parts of an application. Modules help organize code into smaller, manageable pieces, promote code reusability, and facilitate better maintainability and scalability of NodeJS applications. Types of Modules:Core Mod
    2 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences