The path.dirname() method in Node.js is used to retrieve the directory portion of a file path. It removes the last path segment and returns the location of the parent directory, making it useful when working with files and folders programmatically.
- Extracts the directory path from a complete file path.
- Helps locate parent folders without manual string manipulation.
- Commonly used in file system and path management tasks.
Syntax:
path.dirname(path)Parameters:
path: A string representing the file or directory path.
Return Value: Returns a string containing the directory name of the specified path. If the path does not contain a directory component, "." is returned.
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);
In this code,
path.dirname()extracts the directory path from a complete file path.- When only a file name is provided, it returns
"."to represent the current directory. - It also returns the parent directory path when the last segment of a path is removed.
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);
In this code,
- The current file path is displayed using
__filename. path.dirname(__filename)retrieves the directory containing the file.path.dirname(__dirname)retrieves the parent directory of the current directory.
Output:
File name: G:\tutorials\nodejs-path-dirname\index.js
G:\tutorials\nodejs-path-dirname
Directory name: G:\tutorials\nodejs-path-dirname
G:\tutorials
Use Cases of Node.js path.dirname()
- Get parent directory: Extracts the directory path from a complete file path.
- Create related paths: Builds paths for files or folders located in the same directory.
- File system operations: Determines the target directory before reading, writing, or moving files.
Reference: https://nodejs.org/api/path.html#path_path_dirname_path