path module
The path module builds and takes apart file paths correctly on every operating system.
In this page:
Syntax
const path = require('path');
path.join(segment1, segment2)
path.resolve(segment)
path.basename(filePath)
path.extname(filePath)
path module
path.join joins segments with the right separator, path.resolve builds an absolute path, and path.basename, dirname and extname split paths apart. Using path avoids bugs from hand-built strings with slashes.
Note:
Use path.join(__dirname, "file") to reference files next to your script.
Example: path module
const path = require("path");
console.log(path.join("a", "b", "..", "c.txt"));
console.log(path.basename("/tmp/app/index.js"));
console.log(path.extname("photo.final.png"));
console.log(path.dirname("/tmp/app/index.js"));
console.log(path.parse("/home/u/file.txt").name);
// Output:
// a/c.txt
// index.js
// .png
// /tmp/app
// file
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Concatenating paths with plus signs
- Hard-coding backslashes
- Confusing join with resolve
Chapter Summary
- join combines segments
- resolve makes absolute paths
- basename, dirname, extname split paths
- Works across operating systems
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: