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.
- __dirname: The __dirname in a node script returns the path of the folder where the current JavaScript file resides.
- __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.
Javascript
( function () {
const _b = 456;
const _a = 123;
console.log( "a =" , _a);
console.log( "b =" , _b);
})();
|
Output:
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.
Syntax:
console.log(__dirname)
Return Value: It returns the absolute directory name of the current module.
Example 1: Create a JavaScript file app.js and write down the following code.
Javascript
console.log( "Directory Name of the current file is: " ,
__dirname);
|
Output:
C:\Users\Pallavi\Desktop\NODEJS PROJECTS\NodeJS-Projects\Express_Session
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.
Syntax:
console.log(__filename)
Return Value: It returns the absolute filename of the current module.
Example 2: Create a JavaScript file app.js and write down the following code.
Javascript
console.log( "Filename of the current file is: " ,
__filename);
|
Output:
C:\Users\Pallavi\Desktop\NODEJS PROJECTS\NodeJS-Projects\Express_Session\app.js
Reference: https://nodejs.org/api/globals.html#globals_filename