Open In App
Related Articles

Node.js path.dirname() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

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:




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


Output:

/users/admin/website
.
website/post

Example 2:




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


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


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 13 Oct, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials