The Node.js path.parse() method splits a path into its component parts and returns them in an object. It is useful when you need to examine or work with the directory, file name, and extension separately. The output can vary across platforms, and trailing directory separators are ignored during parsing.
- Breaks a path into reusable parts
- Helps extract directory, base name, extension, and file name
- Adapts to platform-specific path formats
Syntax:
path.parse(path)where,
path: The path string to be parsed (throws a TypeError if this parameter is not a string value).
Return Value: An object containing the parsed path components (root, dir, base, ext, and name).
Example 1:
// Node.js program to demonstrate the
// path.parse() method
// Import the path module
const path = require('path');
path1 = path.parse("/users/admin/website/index.html");
console.log(path1);
path2 = path.parse("website/readme.md");
console.log(path2);
In this code,
path.parse()is used on an absolute file path to break it into its path components.- It is then used on a relative file path to extract the same set of components.
- The resulting objects are displayed in the console for both paths.
Output:
{
root: '/',
dir: '/users/admin/website',
base: 'index.html',
ext: '.html',
name: 'index'
}
{
root: '',
dir: 'website',
base: 'readme.md',
ext: '.md',
name: 'readme'
}
Example 2:
// Node.js program to demonstrate the
// path.parse() method
// Import the path module
const path = require('path');
path1 = path.parse("C:\\users\\admin\\website\\index.html");
console.log(path1);
path2 = path.parse("website\\style.css");
console.log(path2);
In this code,
path.parse()is used on a Windows-style absolute file path to extract its components.- It is then used on a relative Windows-style file path to separate its path details.
- The parsed path objects are printed to the console.
Output:
{
root: 'C:\\',
dir: 'C:\\users\\admin\\website',
base: 'index.html',
ext: '.html',
name: 'index'
}
{
root: '',
dir: 'website',
base: 'style.css',
ext: '.css',
name: 'style'
}
Use Cases of path.parse() Method
- Extract path components: Separates a path into parts such as root, directory, file name, and extension.
- File path analysis: Accesses specific portions of a path without manual string manipulation.
- File management: Retrieves file names, extensions, or directory paths for file system operations.
- Path processing: Helps when validating, modifying, or reorganizing file paths programmatically.
Reference: https://nodejs.org/api/path.html#path_path_parse_path