How to Get the Path of Current Script using Node.js ? (original) (raw)
Last Updated : 13 Sep, 2024
In Node JS, getting the path of the current script is useful for **file operations, logging, and configuration. It allows you to access related files or directories reliably, regardless of where your Node.js process was started.
Approach
To get the path of the present script in **node.js we will be using __dirname for the directory path and __filename scope variables for the full path.
- **__dirname: It returns the directory name of the current module in which the current script is located.
- **__filename: It returns the file name of the current module. This is the current module file's absolute path with symlinks (symbolic links) resolved.
Let's Consider the below file structure of the project:
Below examples illustrate the use of **__dirname and **__filename module scope variable in node.js:
**Example 1: Determine the path of the present script while executing **app.js file.
JavaScript ``
// Filename -app.js
// Node.js program to demonstrates how to // get the current path of script
// To get the filename
console.log(Filename is ${__filename}
);
// To get the directory name
console.log(Directory name is ${__dirname}
);
``
**Output:
Filename is D:\DemoProject\app.js
Directory name is D:\DemoProject
**Example 2: Determine the path of the present script while executing **routes\user.js file.
JavaScript ``
// Filename - user.js
// Node.js program to demonstrates how to // get the current path of script
// To get the filename
console.log(Filename is ${__filename}
);
// To get the directory name
console.log(Directory name is ${__dirname}
);
``
**Output:
Filename is D:\DemoProject\routes\app.js
Directory name is D:\DemoProject\routes
Conclusion
We can get the full path of current script file using __filename and the directory path using __directory variables. These appraches provide an effective way to access the the path of the current script and ensures reliable file and directory handling and consistency across different runtime environments.