Path Module

Path Module

The Path module provides a comprehensive set of utilities for working with file and directory paths. File paths can be surprisingly tricky because different operating systems use different path separators (e.g., Windows uses \ while macOS and Linux use /).

By using the path module, you guarantee that your application will construct file paths perfectly across any operating system.


1. Importing the Path Module

No installation is required. Just require it in your script:

const path = require('path');

2. Joining Paths

The most frequently used method is path.join(). It joins multiple string segments into a single path, automatically handling the correct slashes for the current operating system.

path.join()

const path = require('path');

// Safely join folder names and a file name const fullPath = path.join('users', 'admin', 'docs', 'readme.md');

console.log(fullPath); // Output on Windows: users\admin\docs\readme.md // Output on Linux/Mac: users/admin/docs/readme.md


3. Parsing Paths

You can easily extract specific parts of a path using built-in methods:

Extracting Data

const path = require('path');
const myFilePath = '/var/www/html/index.html';

console.log(path.basename(myFilePath)); // "index.html" console.log(path.dirname(myFilePath)); // "/var/www/html" console.log(path.extname(myFilePath)); // ".html"


Exercise

?

Which method should you use to combine multiple directory strings safely across different operating systems?