Node.js __filename object
The __filename in the Node.js returns the filename of the code which is executed. It gives the absolute path of the code file. The following approach covers how to implement __filename in the NodeJS project.
Syntax:
console.log(__filename)
Prerequisites:
- Basic knowledge of Node.js
- Node.js installed (version 12+)
- NPM installed (version 6+)
Return Value: It returns the absolute filename of the current module.
Example 1: Create a JavaScript file index.js and write down the following code:
index.js
// Node.js code to demonstrate the absolute // file name of the current Module. console.log( "Filename of the current file is: " , __filename); |
Run the index.js file using the following command:
node index.js
Output:
Filename of the current file is: C:\Users\Pallavi\Desktop\node_func\app.js
Example 2:
index.js
// Node.js code to demonstrate the absolute // file name of the current Module console.log(__filename); // To show to parts of file using filename. const parts = __filename.split(/[\\/]/); console.log( "This the all the parts " + "present in file :" ,parts); |
Output:
C:\Users\Pallavi\Desktop\node_func\app.js This the all the parts present in file : [ 'C:', 'Users', 'Pallavi', 'Desktop', 'node_func', 'app.js' ]
Reference: https://nodejs.org/api/globals.html#globals_filename
Contact Us