Path Module in Node.js

📘 Node.js 👁 47 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

The path module provides utilities for working with file and directory paths.
It is a core Node.js module, so no installation is required.

const path = require('path');

1. Why Use the Path Module?

  • Handles file paths across operating systems

  • Avoids hard-coded path separators (/ or \)

  • Improves portability and reliability

  • Simplifies path manipulation


2. Path Separators

OSSeparator
Windows\
Linux / macOS/

The path module automatically manages these differences.


3. Common Path Methods

3.1 path.basename()

Returns the last part of a path.

path.basename('/user/docs/file.txt'); // file.txt

3.2 path.dirname()

Returns the directory name of a path.

path.dirname('/user/docs/file.txt'); // /user/docs

3.3 path.extname()

Returns the file extension.

path.extname('file.txt'); // .txt

3.4 path.join()

Joins path segments safely.

path.join('/user', 'docs', 'file.txt'); // /user/docs/file.txt

3.5 path.resolve()

Resolves an absolute path.

path.resolve('docs', 'file.txt'); // /current/path/docs/file.txt

3.6 path.normalize()

Normalizes a path by removing extra slashes.

path.normalize('/user//docs///file.txt'); // /user/docs/file.txt

3.7 path.parse()

Returns an object with path details.

path.parse('/user/docs/file.txt');

Output:

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

3.8 path.format()

Creates a path from an object.

path.format({ dir: '/user/docs', base: 'file.txt' }); // /user/docs/file.txt

3.9 path.isAbsolute()

Checks if a path is absolute.

path.isAbsolute('/user/docs'); // true

4. Important Path Properties

path.sep // Path separator path.delimiter // Environment variable delimiter

5. Absolute vs Relative Paths

Relative Path

./files/data.txt

Absolute Path

C:\users\docs\data.txt

6. Using Path with __dirname

const filePath = path.join(__dirname, 'data', 'file.txt');

✔ Recommended for file operations


7. Best Practices

  • Always use path.join() instead of string concatenation

  • Use __dirname for reliable file access

  • Avoid hardcoding paths


8. Advantages of Path Module

  • Cross-platform compatibility

  • Clean and safe path handling

  • Easy to use

  • Prevents path errors


9. Summary

  • path is a core Node.js module

  • Used to handle and manipulate file paths

  • Works across different operating systems

  • Essential for file system operations


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes