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.
No installation is required. Just require it in your script:
const path = require('path');
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.
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
You can easily extract specific parts of a path using built-in methods:
path.basename(p): Returns the last portion of a path (the file name).path.dirname(p): Returns the directory name of a path.path.extname(p): Returns the extension of the file (e.g., .md, .txt).
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"
Which method should you use to combine multiple directory strings safely across different operating systems?