Node.js – Path Module
Subject: nodejs
Node.js – Path Module
The path
module in Node.js provides utilities for working with file and directory paths. It helps build and manipulate file system paths in a platform-independent way (e.g., /
on Linux/macOS vs \
on Windows).
Why Use the path Module?
- Avoid hardcoding file paths.
- Handle platform-specific path separators.
- Easily join, resolve, normalize, or parse paths.
Importing the path Module
Commonly Used Path Methods
1. path.join()
Joins all given path segments into one path using the appropriate separator.
2. path.resolve()
Resolves a sequence of paths into an absolute path.
3. path.basename()
Returns the last portion of a path (the file name).
4. path.extname()
Returns the file extension.
5. path.dirname()
Returns the directory portion of a path.
6. path.parse()
Parses a file path into an object with properties like root, dir, base, ext, and name.
7. path.format()
Creates a path string from an object (reverse of path.parse()
).
8. path.isAbsolute()
Checks if a path is absolute.
9. path.sep
Returns the platform-specific path segment separator.
Real-World Example
Combining path methods to read a file safely:
Using path.join()
ensures platform compatibility across operating systems.
Key Takeaways
- The
path
module is essential for file path manipulation in a cross-platform environment. - Use
path.join()
andpath.resolve()
for building paths. - Use
path.basename()
,path.extname()
, andpath.dirname()
to extract file components. path.parse()
andpath.format()
help with detailed file path management.