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:
// 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
Please Login to comment...