The Node.js Path module provides useful methods for working with and manipulating file and directory paths. It is especially helpful when building server-side applications or CLI tools where handling paths consistently across different operating systems is important.
Table of Contents
Import the Path module using:
const path = require('path');
Complete Advance AI Topics: Click Here
SQL Tutorial: Click Here
Common Path Methods
path.normalize(p)– Resolves..and.segments and normalizes the path.path.join(...)– Joins multiple path segments and normalizes the resulting path.path.resolve(...)– Creates an absolute path from the provided path segments.path.isAbsolute(p)– Checks whether a path is absolute.path.relative(from, to)– Returns the relative path between two locations.path.dirname(p)/path.basename(p)/path.extname(p)– Returns the directory name, file name, and file extension.path.parse(p)/path.format(obj)– Converts between a path string and a path object.
Node.js Path Example
// path_example.js
const path = require('path');
console.log(path.normalize('/updategadh/projects//node/tab/..'));
console.log(path.join('/updategadh', 'projects', 'node', 'tab', '..'));
console.log(path.resolve('path_example.js'));
console.log(path.extname('path_example.js'));
// Run: node path_example.js
Example Output
/updategadh/projects/node
/updategadh/projects/node
/Users/username/path_example.js
.js
Why path.join() Matters
Using path.join(__dirname, 'file.txt') is better than manually combining path strings. The Path module automatically handles platform-specific path separators, helping your Node.js application work correctly on both Windows and Unix-based operating systems.
Conclusion
YT:- DecodeIT
The Node.js Path module is essential for reliable and cross-platform file and directory handling. Methods such as path.join(), path.resolve(), and path.extname() make it easier to create, analyze, and manipulate paths while reducing common path-related errors.