The Wayback Machine - https://web.archive.org/web/20240927071730/https://www.geeksforgeeks.org/node-js-path-parse-method/
Open In App

Node.js path.parse() Method

Last Updated : 13 Oct, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Previous Article
Next Article

Similar Reads

How to parse a URL into hostname and path in javascript ?
We can parse a URL(Uniform Resource Locator) to access its component and this can be achieved using predefined properties in JavaScript. For Example, the first example parses the URL of the current web page and the second example parses a predefined URL. Example 1:This example parses the URL of the current web page. C/C++ Code <body style="
1 min read
Node.js querystring.parse() Method
The querystring.parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative charac
3 min read
Node.js url.parse(urlString, parseQueryString, slashesDenoteHost) API
The url.parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. Syntax: url.parse( urlString, parseQueryString, slashesDenoteHost) Parameters: This method accepts three parameters as mentioned above and described below: urlString: It holds the URL string which needs to parse.parseQu
2 min read
Node.js Date.parse() API
The date-and-time.Date.parse() is a minimalist collection of functions for manipulating JS date and time module which is used to parse the date according to a certain pattern. Required Module: Install the module by npm or used it locally. By using npm.npm install date-and-time --saveBy using CDN link.<script src="/path/to/date-and-time.min.js"
2 min read
How to Parse JSON using Node.js?
JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configuration files, or databases. In this article, we wi
2 min read
How to Parse Command Line Arguments in Node ?
Command-line arguments, in the context of a command-line interface (CLI), are text strings that provide extra information to a program when it is executed. In Nodejs, these arguments are accessible through an array known as argv (arguments values), where the shell passes all received command-line arguments to the running process. ApproachTo parse t
3 min read
JavaScript JSON parse() Method
The JSON.parse() method in JavaScript is used to parse a JSON string which is written in a JSON format and returns a JavaScript object. Syntax: JSON.parse( string, function ) Parameters: This method accepts two parameters as mentioned above and described below: string: It is a required parameter and it contains a string that is written in JSON form
2 min read
How does the JSON.parse() method works in JavaScript ?
The JSON.parse() method in JavaScript is used to parse a JSON (JavaScript Object Notation) string and convert it into a JavaScript object. JSON is a lightweight data-interchange format that is easy for humans to read and write, and it is also easy for machines to parse and generate. Example: Here, JSON.parse() take a JSON-formatted string (jsonStri
1 min read
JavaScript Date parse() Method
The JavaScript Date parse() method parses a date string and returns the number of milliseconds between the date string and midnight of January 1, 1970, UTC. If the argument is an invalid date string, it returns NaN (Not a Number). Syntax:Date.parse(datestring);Parameters:This method accepts a single parameter: datestring: This parameter holds the d
3 min read
Python | Parse a website with regex and urllib
Let's discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages. Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will gi
2 min read
How to parse URL using JavaScript ?
Given an URL and the task is to parse that URL and retrieve all the related data using JavaScript. Example: URL: https://www.geeksforgeeks.org/courses When we parse the above URL then we can find hostname: geeksforgeeks.com path: /courses Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use
2 min read
How to universally parse JSON into blocks using jQuery ?
In jQuery, to parse any data to any block is carried over by using DOM Insertion methods. Some of DOM Insertion methods are append(), appendTo(), html(), prepend(), prependTo(), text(). To parse JSON into any block is also handled in same way but along with Ajax callback functions and parse.JSON() methods. Here parse.JSON() methods is deprecated in
3 min read
JavaScript SyntaxError - JSON.parse: bad parsing
This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid. Message: SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxEr
2 min read
How to parse and process HTML/XML using PHP ?
In this article, we will learn how to process XML using PHP. We have already learnt the basics of XML and their differences with respect to HTML. Different elements of XML can be learnt from XML Elements to understand the working of the following programs. The simplexml_load_string() function is used to parse the given XML and then the XML object c
2 min read
How to parse HTML file in PHP ?
In this article, we will learn to parse HTML in PHP. What is parsing? Generally parsing is converting one data type to another. It means how we can convert various data types to HTML. For example: Converting string to HTML. Why do we need parsing? To add the dynamic data (HTML content) at a certain point in PHP code, we need parsing. For example: F
2 min read
Moment.js Parse ASP.NET JSON Date
Moment.js is a date library for JavaScript that parses, validates, manipulates, and formats dates. We can use the moment() function passed with a string to parse dates in ASP.NET JSON format. The moment() function is used to create a moment using a string representing a date in ASP.NET JSON format. Syntax: moment( String ) Parameters: It takes a st
1 min read
Backbone.js parse Model
The Backbone.js parse Model is a function that is called whenever a model's data is returned by the server. This function is passed with the response object and returns the model's data. The model has a default implementation of the parse function but we can override this function for flexible usage. Syntax: model.parse( response, options ); Parame
2 min read
Moment.js Parse Date Format Plugin
Parse Date Format is a moment.js plugin to can be used to extract a date/time string's format from a given string. This format can then be later used with other Moment methods. Write the below command in the terminal to install Date Format Plugin: npm install moment-parseformat The following are some of the functions in this plugin: parseFormat The
1 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
Backbone.js parse Collection
The Backbone.js parse Collection is a method that is called by Backbone whenever a Collection's models are returned by the server. The default implementation simply passes the JSON response. We can override it with a new logic to flexibly parse the response. Syntax: collection.parse( response , options ); Parameters: response: It is a raw object wh
2 min read
How to parse HTML DOM with DOMDocument ?
What is DOM Parser? DOM Parser is a JavaScript library that parses HTML or XML documents into their corresponding Document Object Model (DOM). HTML is a markup language that describes the structure of web pages. The DOM is a tree representation of the document. In order to create a page, you need to parse the HTML code into its corresponding DOM us
3 min read
AngularJS $parse Service
The $parse service in AngularJS is a function that takes an expression string and returns a function that can be used to parse and evaluate the expression. The expression string can contain variables, operators, and function calls. To use the $parse service, you first need to inject it into your AngularJS component as a dependency. For example, you
3 min read
What is the difference between the $parse, $interpolate and $compile services?
In AngularJS applications, the $parse, $interpolate and $compile services are the most important components as these services are used for data binding. Here, the $parse is mainly responsible for parsing and evaluating the expressions in the context of the application's scope. The $interpolate handles the interpolation of expressions and the $compi
6 min read
How to parse JSON Data into React Table Component ?
In React parsing JSON Data into React Table Component is a common task to represent data by building UI components. Prerequisites:NPM & Node JSReact JSJSON parse()Approach:We will create react table components and parse a JSON file consisting of objects with id, name, and city associated uniquely. We will use the .map() function to parse each o
2 min read
Why is Parse Server the future of Backend As A Service?
Are you a developer?  Have you ever coded your way through a web or a mobile application that is really cool and scalable? Being an amateur or a pro is irrelevant in this context. If your answer to the first question is “Yes”, then this article is just for you. Go ahead and read what I have got to say. Have you heard of the term, “Parse Server”? Ev
8 min read
How to Parse Float with Two Decimal Places in TypeScript ?
In Typescript, parsing float with two decimal places refers to mainly converting the float number with two digits after the decimal points. There are various approaches to parse float with two decimal places in TypeScript which are as follows: Table of Content Using Math.round methodUsing toFixed methodUsing Number constructorUsing bitwise OR Opera
3 min read
How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ?
To parse HTTP Cookie header we will spilt the cookies data and create objects from the key-value extracted from cookies. Cookies are simply small text files that a web server sends to the user's browser. They contain the following data. Name-value pair with actual data.The expiry date for when the cookie becomes invalid.Domain and path of the serve
3 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to parse a CSV File in PHP ?
In this article, we learn to parse a CSV file using PHP code, along with understanding its basic implementation through examples.   Approach: The following approach will be utilized to parse the CSV File using PHP, which is described below: Step 1. Add data to an Excel file. The following example is given for sample data having Name and Coding Scor
3 min read
How to Catch JSON Parse Error in JavaScript ?
JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However, parsing JSON data can sometimes lead to errors, e
1 min read