Node.js path.parse() Method
Last Updated :
13 Oct, 2021
Improve
The path.parse() method is used to return an object whose properties represent the given path. This method returns the following properties:
javascript
Output:
javascript
Output:
- root (root name)
- dir (directory name)
- base (filename with extension)
- ext (only extension)
- name (only filename)
path.parse( path )Parameters: This method accepts single parameter path which holds the file path that would be parsed by the method. It throws a TypeError if this parameter is not a string value. Return Value: This method returns an object with the details of the path. Below examples illustrate the path.parse() method in node.js: Example 1: On POSIX
// 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);
{ root: '/', dir: '/users/admin/website', base: 'index.html', ext: '.html', name: 'index' } { root: '', dir: 'website', base: 'readme.md', ext: '.md', name: 'readme' }Example 2: On Windows
// 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);
{ root: 'C:\\', dir: 'C:\\users\\admin\\website', base: 'index.html', ext: '.html', name: 'index' } { root: '', dir: 'website', base: 'style.css', ext: '.css', name: 'style' }Reference: https://nodejs.org/api/path.html#path_path_parse_path