The path module provides utilities for working with file paths. Here's how to use it effectively.
Basic Path Operations#
Path Parsing and Formatting#
Relative and Absolute Paths#
Path Normalization#
Cross-Platform Handling#
Common Patterns#
Working with __dirname and __filename#
Path Validation#
URL and Path Conversion#
Glob Pattern Helpers#
Best Practices#
Cross-Platform:
✓ Always use path.join() for paths
✓ Use path.sep for separators
✓ Avoid hardcoded slashes
✓ Test on both platforms
Security:
✓ Validate paths from user input
✓ Use isWithinDirectory checks
✓ Sanitize filenames
✓ Resolve before validation
Patterns:
✓ Use path.resolve() for absolute paths
✓ Use path.parse() for components
✓ Store __dirname in ES Modules
✓ Normalize before comparing
Avoid:
✗ String concatenation for paths
✗ Assuming path separator
✗ Trusting user-provided paths
✗ Using relative paths without resolve
Conclusion#
The path module is essential for cross-platform file operations. Use path.join() and path.resolve() instead of string concatenation, validate user input to prevent path traversal, and use path.parse() for extracting components. Always consider cross-platform compatibility in your path handling code.