Related Articles

Related Articles

How to get the path of current script using Node.js ?
  • Last Updated : 31 Jan, 2020

We can get the path of the present script in node.js by using __dirname and __filename module scope variables.

  • __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.

app.js file:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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}`);

chevron_right


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.

user.js file:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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}`);

chevron_right


Output:

Filename is D:\DemoProject\routes\app.js
Directory name is D:\DemoProject\routes
My Personal Notes arrow_drop_up
Recommended Articles
Page :