Skip to content
Related Articles

Related Articles

Node.js | path.parse() Method
  • Last Updated : 28 Jan, 2020

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




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

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




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

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :