The Path Module
๐ Covered in this chapter:
path.join() ยท path.resolve() ยท path.basename() ยท path.dirname() ยท Cross-Platform Paths
Handle file paths safely and consistently across operating systems using Node's built-in path module.
1The Path Module โ What You'll Learn
Handle file paths safely and consistently across operating systems using Node's built-in path module.
Here's everything this chapter covers, in the order you'll learn it:
- Why manual path string handling is unsafe
- path.join() to combine path segments
- path.resolve() to get an absolute path
- path.basename() to extract a filename
- path.dirname() to extract a directory
- path.extname() to extract a file extension
- Cross-platform path handling (Windows uses \, Unix uses /)
- __dirname alternatives in ES Modules
- Safe path handling
- Preventing path traversal attacks
2Working Example
๐ป Example: The Path Module
JavaScript
โถ Run in Compiler
import path from "node:path";
const filePath = path.join("src", "routes", "users.js");
console.log(filePath);
console.log(path.basename(filePath));
console.log(path.dirname(filePath));
console.log(path.extname(filePath));
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- Always use path.join() instead of manually concatenating strings with '/' โ it automatically handles the correct separator for the OS.
- In ES Modules, __dirname isn't available directly โ use `import.meta.url` with `fileURLToPath()` instead.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about the path module?
Focus on: path.join() ยท path.resolve() ยท path.basename() ยท path.dirname() ยท Cross-Platform Paths. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for the path module?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.