What is the purpose of __filename variable in Node.js ?
Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.
In this article, we will learn about the purpose of __filename variable in NodeJS.
Prerequisites:
NodeJS Installed
__filename
__filename is a little bit clear from its name that it is somewhere associated with the name of the file/code which we are executing. It returns the absolute path of the code file. The following approach covers how to implement __filename in the NodeJS project.
Syntax:
console.log(__filename)
Return Value: It returns the absolute filename of the current module.
Purpose:
- To get the absolute path of the current file/code.
- To get the name of the file currently executing.
Example 1:Write this code in a file name fileNameDemo.jsx. Now we will try to get this name using __filename.
Javascript
console.log( "w3wiki" ); console.log( "Name of the file which we" + " are currently executing is " ); console.log(__filename) |
How to run this?
- Open Terminal
- Go to the directory where you have saved this file using cd command.
- Now just run this file by using
node file_name
Output:
Example 2: In this example, we will use split function to split the directory returned by __filename.
Javascript
console.log( "w3wiki" ); // To show to parts of file using filename. const parts = __filename.split(/[\\/]/) console.log( "This the all the parts " + "present in file :" ,parts); |
Output:
Example 3: In this example, we will simply display the filename not the directory. Firstly, we will get the directory using __filename then split it. Then we will print the last index of the split array.
Javascript
console.log( "w3wiki" ); // To show exact name of the file. const parts = __filename.split(/[\\/]/) console.log( "FileName is : " + parts[parts.length-1]); |
Output:
Contact Us