__dirname, module Paths & import.meta.url
6 min read
__dirname and Module Paths
In CommonJS, Node.js injects __dirname (the directory of the current file) and __filename (the full file path) into every module. These are essential for building paths that work regardless of where your script is called from.
js
// CommonJS
const path = require("path");
console.log(__filename); // /home/user/app/index.js
console.log(__dirname); // /home/user/app
const configPath = path.join(__dirname, "config", "app.json");
console.log(configPath); // /home/user/app/config/app.jsonESM Equivalent
ESM does not provide __dirname. Use import.meta.url together with the url and path modules to recreate it.
js
// ESM
import { fileURLToPath } from "url";
import { dirname, join } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const configPath = join(__dirname, "config", "app.json");
console.log(configPath);Always build file paths with path.join rather than string concatenation to ensure cross-platform compatibility on Windows, macOS, and Linux.
Ready to test yourself?
Practice Node.js— quiz & coding exercises