Node.js path.dirname() Method
Last Updated :
13 Oct, 2021
Improve
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:
javascript
Output:
javascript
Output:
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.
// 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);
/users/admin/website . website/postExample 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);
File name: G:\tutorials\nodejs-path-dirname\index.js G:\tutorials\nodejs-path-dirname Directory name: G:\tutorials\nodejs-path-dirname G:\tutorialsReference: https://nodejs.org/api/path.html#path_path_dirname_path