Node.js Path Module

📁 Node.js – Path Module

The Path module in Node.js provides utilities for working with file and directory paths.

It helps you:

  • Join paths

  • Resolve absolute paths

  • Get file extensions

  • Get file names

  • Normalize paths

  • Work with OS-specific path formats

It’s a built-in module → no installation required.


1. Import the Path Module



🔹 2. path.join()

Joins multiple path segments into a single path
(Automatically handles slashes)

Output:

folder/subfolder/file.txt

🔹 3. path.resolve()

Returns an absolute path

Example output:

C:\Users\Vipul\project\file.txt

🔹 4. path.basename()

Returns the file name

Output:

document.txt

Get file name without extension:


🔹 5. path.dirname()

Returns directory name of a path

Output:

/home/docs

🔹 6. path.extname()

Returns file extension

Output:

.html

🔹 7. path.parse()

Returns an object with full path details

Output:

{
root: '/',
dir: '/home/user',
base: 'file.txt',
ext: '.txt',
name: 'file'
}

🔹 8. path.format()

Opposite of parse()
Creates a path string from an object


 

console.log(path.format(obj));

Output:

/home/user/file.txt

🔹 9. path.normalize()

Fixes incorrect/messy paths

Output:

folder/sub/file.txt

🔹 10. path.isAbsolute()

Checks if a path is absolute

Output:

true

🔹 11. path.sep

Path separator used by OS

  • Windows → \

  • Linux/Mac → /


🔹 12. path.join() vs path.resolve()

Featurejoin()resolve()
Combines path parts
Returns absolute path
Handles .. or .

Example:


 


Complete Example


 


🎯 Summary Table

MethodDescription
join()Join multiple paths
resolve()Get absolute path
basename()File name
dirname()Folder name
extname()File extension
parse()Break path into parts
format()Create path from parts
normalize()Fix path formatting
isAbsolute()Check absolute path
sepSystem path separator

You may also like...