__dirname & Paths

__dirname and __filename give the location of the current file.

Syntaxpath.join(__dirname, 'data.json')

Inside a CommonJS module, two globals tell you where the file lives:

  • __dirname — the absolute path of the folder containing the file.
  • __filename — the absolute path of the file itself.

Why they matter

Relative paths in file operations are resolved from where you ran node, not where the file is. Building paths from __dirname makes them reliable no matter where the program is started.

Example

Example · javascript
const path = require('path');

console.log('Folder:', __dirname);
console.log('File:', __filename);

// Build a safe, absolute path to a nearby file
const dataPath = path.join(__dirname, 'data', 'users.json');
console.log(dataPath);

When to use it

  • A config loader uses `path.join(__dirname, '../config/default.json')` to build an absolute path to a sibling config file that works regardless of where the script is invoked.
  • A static file server resolves asset paths relative to `__dirname` so the correct files are served when the server is started from a different working directory.
  • A CLI tool uses `__filename` to print its own version by reading the `package.json` in its own directory.

More examples

__dirname and __filename basics

Shows the values of `__filename` and `__dirname` -- both are absolute paths injected by Node's module wrapper.

Example · js
// /home/user/project/src/app.js
console.log(__filename);
// /home/user/project/src/app.js

console.log(__dirname);
// /home/user/project/src

Build a safe file path

Uses `__dirname` and `path.join()` to build an absolute path to a config file, safe regardless of cwd.

Example · js
const path = require('path');

// Load a file relative to this module, not the cwd
const configPath = path.join(__dirname, '..', 'config', 'app.json');
const { readFileSync } = require('fs');
const config = JSON.parse(readFileSync(configPath, 'utf8'));
console.log(config);

ESM equivalent with import.meta

Recreates `__dirname` inside an ES module using `import.meta.url` and `fileURLToPath`.

Example · js
// In an ES module (.mjs or type:module)
import { fileURLToPath } from 'url';
import { dirname, join }  from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname  = dirname(__filename);

console.log(join(__dirname, 'data', 'seed.json'));

Discussion

  • Be the first to comment on this lesson.