0
0
NodejsConceptBeginner · 3 min read

__filename in Node.js: What It Is and How It Works

__filename in Node.js is a special variable that holds the full path and filename of the current module file. It helps you know exactly where the running script is located on your computer.
⚙️

How It Works

Think of __filename as a name tag for the file your Node.js program is running. It tells you the exact location of that file on your computer, including the folder path and the file name itself.

This is useful because your program might be running in different folders or machines, and you want to know where your script lives to work with files or logs relative to it. Node.js automatically sets this variable for every module, so you don't have to do anything special to get it.

💻

Example

This example shows how __filename prints the full path of the current file when you run it.

javascript
console.log('__filename:', __filename);
Output
__filename: /Users/yourname/projects/example/index.js
🎯

When to Use

You use __filename when you need to know the exact file path of the script running your code. For example, if you want to read or write files relative to your script's location, or log where your program is running from.

It is also helpful in debugging to confirm which file is executing, especially in larger projects with many files.

Key Points

  • __filename gives the full path of the current module file.
  • It is set automatically by Node.js for every file.
  • Useful for file operations and debugging.
  • Always returns an absolute path, not relative.

Key Takeaways

__filename holds the full path of the current Node.js file.
It helps you find where your script is running on your computer.
Use it for file handling and debugging in your Node.js apps.
Node.js sets it automatically for every module file.