Node.js __filename object
Last Updated :
06 Apr, 2021
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
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
console.log(__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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...