Back to results for “CLI Tools & Scripting with Node.js”
Node.js › File System & File Processing

What is the difference between an absolute path and a relative path in Node.js, and how does __dirname help resolve paths reliably?

Beginner

Answer

A relative path is interpreted relative to the current working directory (which can vary depending on how and from where a script is run), while an absolute path specifies the complete, unambiguous location from the filesystem root -- __dirname (in CommonJS; import.meta.dirname in ESM) always resolves to the directory containing the currently executing file, letting you build reliable absolute paths relative to the script's own location regardless of the working directory the process happens to be started from.
// Fragile: depends entirely on where the script happens to be run from
fs.readFileSync('./config.json');

// Reliable: always resolves relative to this specific file's actual location
fs.readFileSync(path.join(__dirname, 'config.json'));
Real-world example A CLI tool that worked fine when run from its own directory broke when a user invoked it from a different working directory, since its relative path assumed the wrong base location; switching to path.join(__dirname, ...) fixed it by anchoring the path to the script's own location instead.

Common follow-ups: What is the ESM equivalent of __dirname, given __dirname isn't available in ES Modules by default?;Why does the current working directory (process.cwd()) differ from __dirname, and when would you actually want to use process.cwd() instead?