Topic 32 of 55
Path Module Utilities
Overview
The `path` module provides utilities for working with file and directory paths. It is crucial for building cross-platform apps because Windows uses backslashes `\` for paths, while Mac/Linux use forward slashes `/`. The `path` module handles this automatically.
Syntax
javascript
const path = require('path');
// 1. path.join(): Concatenates paths safely across operating systems
const fullPath = path.join(__dirname, 'public', 'images', 'logo.png');
// Mac/Linux: /user/app/public/images/logo.png
// Windows: C:\user\app\public\images\logo.png
// 2. path.resolve(): Resolves a sequence of paths into an ABSOLUTE path
const absolute = path.resolve('public', 'scripts');
// Useful when a library strictly requires an absolute path.
// 3. Extracting parts of a path
const filename = '/users/test/index.html';
console.log(path.basename(filename)); // 'index.html'
console.log(path.extname(filename)); // '.html'
console.log(path.dirname(filename)); // '/users/test'Common Pitfalls
- Never construct file paths via manual string concatenation (e.g., `__dirname + '/public/file.txt'`). It will break on Windows. Always use `path.join()`.
- When using ES Modules, `__dirname` is not available. You must construct it manually using `import.meta.url` and `fileURLToPath` from the `url` module.
Real-World Example
Parsing a file path into an object:
example
javascript
const path = require('path');
const parsedPath = path.parse('/home/user/dir/file.txt');
console.log(parsedPath);
/*
{
root: '/',
dir: '/home/user/dir',
base: 'file.txt',
ext: '.txt',
name: 'file'
}
*/
// You can modify the object and format it back into a string
parsedPath.name = 'new_file';
const newPath = path.format(parsedPath);
console.log(newPath); // '/home/user/dir/new_file.txt'