Absolute vs. Relative Paths
Mastering filesystem paths: root slash (/), current directory (.), parent directory (..), home shortcut (~), and path resolution rules.
Absolute vs. Relative Paths
A path is a string specifying the unique location of a file or folder in a filesystem hierarchy. Every file path in software engineering is either absolute or relative.
1. Absolute Paths
An absolute path specifies the complete location of a file starting from the root of the filesystem. It always points to the exact same file, regardless of where your current working directory is.
Unix/macOS/Linux:
Always begins with a forward slash /:
/Users/alex/Coding/OpenDevDocs/package.json
/var/log/nginx/access.log
/etc/hostsWindows:
Begins with a drive letter and colon C:\:
C:\Users\alex\Coding\OpenDevDocs\package.json2. Relative Paths
A relative path specifies the location of a target file relative to your current working directory (cwd).
Special path tokens:
.(single dot): The current working directory...(double dot): The immediate parent directory (one level up).~(tilde): Shortcut representing the current user's home directory (/Users/alexor/home/alex).
Relative Path Examples
Assuming your current directory is /Users/alex/Coding/OpenDevDocs/src:
| Target File | Relative Path from src/ | Explanation |
|---|---|---|
src/components/Header.tsx | ./components/Header.tsx | Look in components inside current directory |
package.json (in root) | ../package.json | Go up one level to OpenDevDocs/, then find package.json |
.gitignore (in root) | ../.gitignore | Go up one level to root |
~/.zshrc (in user home) | ~/.zshrc | User home directory config |
3. Path Resolution in Code & Imports
Node.js / TypeScript ES Modules:
// Relative import: look in sibling directory
import { Button } from "../components/ui/button";
// Path alias (configured in tsconfig.json paths): resolves from project root
import { Button } from "@/components/ui/button";Node.js Filesystem Path Resolution:
import path from "node:path";
// ❌ Risky: relative to where the terminal process was started
const data = fs.readFileSync("./data.json");
// ✅ Safe: absolute path resolved relative to current module location
const dataPath = path.resolve(import.meta.dirname, "./data.json");
const data = fs.readFileSync(dataPath);4. Common Mistakes
- Assuming
.means project root in scripts: When executingnode server.jsfrom a different folder,./resolves to the terminal's execution folder, NOT the script's directory. Always usepath.resolve(__dirname, ...)orimport.meta.dirname. - Hardcoding OS backslashes (
\): Hardcoding\breaks on Linux/macOS and in Docker containers. Always usepath.join("src", "components")or standard forward slashes/.