__dirname and __filename: Path Anchors in Node.js
__dirname and __filename act as GPS for your Node.js files, giving you the absolute path to the current file and its directory. This is essential for reliably loading adjacent files, like templates or configs. The main gotcha: they don't exist in ES Modules.
WHY IT EXISTS: Node.js scripts can be executed from any directory. If your code tries to read a file using a relative path like './data.json', it resolves from the current working directory, not your script's location. This means your app breaks if you run it from a different folder. __dirname and __filename were created to solve this by providing a reliable anchor to the script's actual location on the filesystem.
THE MENTAL MODEL: Think of __dirname and __filename as the built-in GPS coordinates for your code files. Instead of guessing where you are based on your starting point (the current working directory), they give you an absolute, unchanging address for the file and its containing folder. This ensures that file paths constructed from them always point to the right place.
HOW IT WORKS: In any CommonJS module, Node.js makes two string variables available. __filename is the absolute path to the file being executed, for example, '/var/www/my-app/server.js'. __dirname is the absolute path to the directory containing that file, so in this case, '/var/www/my-app'. It's effectively the same as running path.dirname(__filename).
WHEN TO USE IT: The primary use case is creating reliable paths to other files your application needs. Always use them with the path.join() method to ensure cross-platform compatibility (Windows vs. Unix slashes). For example, to serve a 'public' folder in an Express app, you would use path.join(__dirname, 'public').
WHEN NOT TO USE IT: The most critical footgun is that __dirname and __filename DO NOT exist in ES Modules (when you use import/export syntax or have "type": "module" in package.json). Attempting to use them will cause a ReferenceError. In ESM, you must derive them yourself using import.meta.url. For example: import { fileURLToPath } from 'url'; import { dirname } from 'path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename);.
ONE CANONICAL EXAMPLE: A classic Express.js web server needs to serve static assets like CSS and client-side JavaScript. To do this reliably, you give it an absolute path to the assets folder, constructed using __dirname.
const express = require('express'); const path = require('path'); const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, () => console.log('Server running on port 3000'));
This code works no matter where you run the node command from.
Read the original → nodejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.