Node.js | path.dirname() Method

The path.dirname() method is used to get the directory name of the given path. It ignores the respective platform’s trailing directory separators.

Syntax:

path.dirname( path )

Parameters: This function accepts one parameter as mentioned above and described below:

  • path: It is the file path that would be used to extract the directory name. It throws a TypeError if this parameter is not a string value.

Return Value: It returns a string with the directory of the path.

Below programs illustrate the path.dirname() method in Node.js:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the    
// path.dirname() method 
     
// Import the path module
const path = require('path');
   
// Complete file path
path1 = path.dirname("/users/admin/website/index.html");
console.log(path1)
   
// Only file name
// returns a period (.)
path2 = path.dirname("readme.md");
console.log(path2)
   
// Path with file not specified
path3 = path.dirname("website/post/comments")
console.log(path3);

chevron_right


Output:

/users/admin/website
.
website/post

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the    
// path.dirname() method 
     
// Import the path module
const path = require('path');
   
console.log("File name:", __filename);
path1 = path.dirname(__filename);
console.log(path1);
   
console.log("Directory name:", __dirname);
path2 = path.dirname(__dirname);
console.log(path2);

chevron_right


Output:

File name:  G:\tutorials\nodejs-path-dirname\index.js
G:\tutorials\nodejs-path-dirname
Directory name:  G:\tutorials\nodejs-path-dirname
G:\tutorials

Reference: https://nodejs.org/api/path.html#path_path_dirname_path

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.