__dirname & __filename (Node.js)

__dirname is the absolute path of the directory containing the current module, and __filename is the full path of the current file. They let you reference files relative to the module's own location.

Node.js

Relative paths in Node resolve against the process's working directory (where you ran node), which is not always where your script lives. __dirname fixes this by giving the directory of the current file, so path.join(__dirname, 'config.json') always finds the file next to your module, no matter where Node was launched.

__filename is the full path including the filename, useful for logging which file is executing. Both are available automatically in CommonJS modules without importing anything.

In ES Modules these two variables do not exist. You reconstruct them from import.meta.url: const __dirname = path.dirname(url.fileURLToPath(import.meta.url)). This is a common gotcha when converting CommonJS code to ESM.

Syntax

path.join(__dirname, "file.txt")

Examples

JavaScript

const path = require("path");
console.log(__dirname);  // /home/user/project/src
console.log(__filename); // /home/user/project/src/app.js
const cfg = path.join(__dirname, "config.json");

Learn it in a lesson

See also

Back to the Dictionary