The path module provides utilities for working with file and directory paths. Here's how to use it effectively.
Import
path.join()
path.resolve()
path.basename()
path.dirname()
path.extname()
path.parse()
path.format()
path.relative()
path.isAbsolute()
path.normalize()
path.sep and path.delimiter
Cross-Platform Paths
Common Patterns
Best Practices
Cross-Platform:
✓ Always use path.join()
✓ Use path.sep when needed
✓ Test on multiple OS
✓ Avoid hardcoded separators
Security:
✓ Validate user-provided paths
✓ Prevent path traversal
✓ Use path.resolve for absolute
✓ Sanitize file names
ES Modules:
✓ Use import.meta.url
✓ Convert to __dirname
✓ Use fileURLToPath
✓ Handle Windows paths
Avoid:
✗ String concatenation for paths
✗ Hardcoded '/' or '\\'
✗ Trusting user input
✗ Mixing path styles
Conclusion
The path module is essential for cross-platform file path handling. Use path.join() for combining paths, path.resolve() for absolute paths, and path.parse()/path.format() for manipulation. Always use path module methods instead of string concatenation to ensure cross-platform compatibility.