Node.js | path.parse() Method

The path.parse() method is used to return an object whose properties represent the given path. This method returns the following properties:

  • root (root name)
  • dir (directory name)
  • base (filename with extension)
  • ext (only extension)
  • name (only filename)

The values of these properties may be different for every platform. It ignores the platform’s trailing directory separators during parsing.

Syntax:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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: On Windows

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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'
}

Reference: https://nodejs.org/api/path.html#path_path_parse_path

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.