In this article, we will see what double underscore (__) is in front of a variable in Node.js.
NodeJS is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It is used for traditional websites and back-end API services but was designed with real-time, push-based architectures in mind.
Prerequisite: You can learn how to install Nodejs from here.
Double underscore (__) in front of a variable is a convention. It is used for the global variables (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define a private variable.
There were only two variables in (called global objects) with double underscores in Node. js.
- __filename: The __filename in Node.js returns the filename of the code which is executed. It gives the absolute path of the code filename.
1. Underscore(_) – Private Variable
Below is an example of a private variable.
const _b = 456;
const _a = 123;
a = 123
b = 456
2. Double underscore (__) – Global Variable.
Below is an example of both the variable
The __dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.
Return Value: It returns the absolute directory name of the current module.
"Directory Name of the current file is: "
The __filename in Node.js returns the filename of the code that is executed. It gives the absolute path of the code file. The following approach covers how to implement __filename in the NodeJS project.
Return Value: It returns the absolute filename of the current module.
"Filename of the current file is: "