What is __dirname and __filename in Node.js?

Answer

__dirname is a global variable in Node.js CommonJS modules that contains the absolute directory path of the currently executing module's file. __filename contains the absolute path of the currently executing file, including the filename itself. They are extremely useful for constructing file paths relative to the current module, avoiding issues with the current working directory changing: const configPath = path.join(__dirname, "config", "settings.json");. This is preferable to relative paths like "./config/settings.json", which are resolved relative to process.cwd() (the directory from which Node.js was launched), not the module's location. Note: In ES Modules (.mjs or "type": "module"), __dirname and __filename are not available. The equivalent is: import.meta.url + new URL() + fileURLToPath().