Module-relative resources
Load configuration, templates, or other files stored beside a CommonJS module regardless of the launch directory.
Node.js · Pipe
__dirname is a CommonJS module-local string containing the directory of the currently executing script. Use it to build paths anchored to that module instead of the process's working directory.
In a CommonJS module, __dirname is a string containing the directory of the currently executing module. It is scoped to each module rather than being a true global, so dependencies receive paths based on their own locations; combine it with node:path to create module-relative paths.
__dirnameA string containing the directory name of the currently executing script.
__dirname in version 0.1.27.__dirname according to the dependency module's own location.node command was launched.console.log(__dirname);
console.log(path.join(__dirname, 'config.json'));Prints the current CommonJS module directory and builds an absolute path to a file located beside that module.
Load configuration, templates, or other files stored beside a CommonJS module regardless of the launch directory.
Give each package or dependency a path rooted in its own installed module directory.
__dirname contain?__dirname is a CommonJS-provided string containing the directory of the currently executing script. It is local to the module, so each module resolves it relative to its own file.
Follow-up: How would you construct a path to a sibling file? Use path.join(__dirname, 'file.ext'), then pass the result to the relevant filesystem API.
__dirname a true global?No. The documentation describes it as local to each module rather than an actual global. A dependency therefore sees its own module directory, not the application's directory.
Follow-up: What should code use when it needs the application's working directory? Use process.cwd(), because that represents the process working directory rather than the module location.
__dirname instead of a relative path?It is useful for paths that should remain anchored to the module's location, such as configuration files or assets shipped beside the source file. This avoids depending on the caller's current working directory.
Follow-up: What changes when the same code is packaged as a Node.js single executable application? The official documentation notes that an injected module's __dirname equals the directory name of process.execPath.
__filenamepath.dirname()process.cwd()