Skip to content
Related Articles

Related Articles

Improve Article

What does double underscore (__) in front of a variable in Node.js ?

  • Difficulty Level : Medium
  • Last Updated : 09 Jul, 2021

In this article, we will see what does double underscore (__) 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 from here.

Double underscore (__) in front of a variable is a convention. It is used for global variable (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define 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 the 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 example of private variable.

Javascript




(function() {
    
    // Define two variable
    var _b = 456;
    var _a = 123;
    console.log("a =",_a); // => 123
    console.log("b =",_b);
})();

Output:

a = 123
b = 456

2. Double underscore (__) – Global Variable.

Below is 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.

app.js




// Node.js code to demonstrate the absolute
// file name of the current Module.
console.log("Directory Name of the current file is: ",
    __dirname);

Output:

C:\Users\Pallavi\Desktop\NODEJS PROJECTS\NodeJS-Projects\Express_Session

The __filename in the 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




// Node.js code to demonstrate the absolute
// file name of the current Module.
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




My Personal Notes arrow_drop_up
Recommended Articles
Page :