path
module in Node.js provides utilities to work with file and directory paths.
It is built-in and can be imported using:
const path = require('path');
✅ path.basename(path)
Returns: The filename from a full path.
Use Case: Extract file name during file upload logging.
path.basename('C:\\temp\\abcd.html');
// Output: 'abcd.html'
✅ path.dirname(path)
Returns: The directory portion of the path.
Use Case: Get parent directory before saving a file.
path.dirname('foo\\abcd\\test.html');
// Output: 'foo\\abcd'
✅ path.extname(path)
Returns: The file extension from the path.
Use Case: Validate file type before processing upload.
path.extname('test.html'); // '.html'
path.extname('file.name.md'); // '.md'
path.extname('.hiddenfile.txt'); // '.txt'
path.extname('filename'); // ''
path.extname('.config'); // ''
✅ path.format(pathObject)
Returns: A full path string from a path object.
Use Case: Dynamically construct a path from user input.
path.format({
dir: 'foo\\dir',
base: 'abcd.txt'
});
// Output: 'foo\\dir\\abcd.txt'
✅ path.isAbsolute(path)
Returns: true
if the path is absolute, else false
.
Use Case: Ensure path safety before file operations.
path.isAbsolute('C:\\folder'); // true
path.isAbsolute('.'); // false
path.isAbsolute(''); // false
✅ path.join([...paths])
Returns: A normalized path by joining segments.
Use Case: Construct safe file paths across platforms.
path.join('foo', 'bar', 'file.txt');
// Output: 'foo\\bar\\file.txt'
path.join('foo', {}, 'file');
// Throws TypeError
✅ path.relative(from, to)
Returns: The relative path from one location to another.
Use Case: Generate relative paths for reports or internal links.
path.relative('C:\\a\\b', 'C:\\a\\c\\d');
// Output: '..\\c\\d'
✅ path.resolve([...paths])
Returns: An absolute path from right-to-left evaluated segments.
Use Case: Use in CLI or config files to get full absolute paths.
path.resolve('foo', 'bar');
// Output: 'C:\\current\\dir\\foo\\bar'
✅ path.sep
Returns: The platform-specific path separator.
Use Case: Write cross-platform code that involves file system paths.
console.log(path.sep);
// Output: '\' on Windows, '/' on macOS/Linux
🔚 Conclusion
The path
module is extremely helpful when dealing with file systems in Node.js. Whether you're building CLI tools, managing file uploads, or automating directory structures, these methods ensure your code is clean, cross-platform, and error-free.
📌 Save this as a quick reference or bookmark it for later!
Comments
Post a Comment