Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Globals and Console

Node.js __dirname and __filename

Reference for __dirname and __filename in Node.js CommonJS: what they contain, why they are missing in ES modules, and the modern replacements.

__filename is the absolute path of the file that is running, and __dirname is the absolute path of the folder that contains it. They are the reliable way to build paths relative to your source code, because process.cwd() depends on where the user launched the program, not on where the file lives.

They exist only in CommonJS files. In an ES module they are not defined; use import.meta.dirname and import.meta.filename (Node 20.11+ and 21.2+) instead.

NODE
// cjs
console.log(typeof __dirname, typeof __filename); // string string

Try it

Node.js CommonJS: both values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js ES modules: the replacements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
__filename // string
__dirname  // string
Name Description
__filename Absolute path of the current module file, with symbolic links resolved.
__dirname Same as path.dirname(__filename): the absolute path of the containing folder, without a trailing separator.

Returns: strings, using the platform separator (\ on Windows, / elsewhere).

Edge cases: in an ES module, reading __dirname throws ReferenceError: __dirname is not defined in ES module scope. They are not properties of globalThis; Node passes them as parameters to the function that wraps each CommonJS file, so they differ per file.

Usage notes

  • Use them for files shipped with your code: templates, SQL files, JSON fixtures, static folders. path.join(__dirname, 'views') works from any working directory.
  • Use process.cwd() for files the user names on the command line; relative paths there should resolve against where they ran the command.
  • Never build paths with + '/'. path.join() and path.resolve() handle separators for every platform.
  • In ESM prefer import.meta.dirname. It is a plain string, so no fileURLToPath call is needed. import.meta.url is a file: URL string, which is not a path.
  • Bundlers change the meaning. After bundling, __dirname may point to the output folder; check your tool's option for keeping or rewriting it.
  • REPL and -e code has no file, so there __filename is not meaningful.
  • Both are strings, not URLs. Do not pass them to new URL() directly; use pathToFileURL() from node:url.