×

Node.js Path Module

Understanding the path Module in Node.js

The path module is a built-in module of Node.js that provides various methods to interact with the files and directory path names on the device’s file system. The path module has numerous useful functionalities and methods that can easily access and manipulates paths present in the file system.

Since the path module is one of the core modules in Node.js, therefore, we can import the module using the following syntax:

const path = require(‘path’);

Some Properties of the path module

  • The path module provides sep property to represent the platform-specific path-segment separator:
path.sep

The path.sep returns ‘/’ on Linux and macOS, and ‘\’ on Windows.

  • The path module also provides delimiter property to represent the path delimiter:
path.delimiter

The path.delimiter returns ‘:’ on  Linux / macOS, and ‘;’ on Windows.

  • The path module allows access to POSIX specific applications:
path.posix
  • The path module also provides access to Windows-specific applications:
path.win32

 Understanding methods of path module

We can use many methods in the path module for interacting with the path of a file system. Some of them are list below:

  • path.basename(path[, ext])
  • path.parse(path)
  • path.format(pathObject)
  • path.extname(path)
  • path.dirname(path)
  • path.relative(from, to)
  • path.normalize(path)
  • path.isAbsolute(path)
  • path.join([...paths])
  • path.resolve([...paths])

Let’s discuss these methods in brief.

1. path.basename(path[, ext])

The path.basename() method is used to return the trailing segment of the specified path. This method works similar as the Unix basename command. For Example:

// Importing the 'path' module
const path = require ('path');
// This method returns basename
const mybasename = path.basename('/ffolder/sfolder/tfolder/good.html');
console.log("This is the base-name: " + mybasename);
To execute the above script file, type the following command:
$ node path.js

The Output should look as follows:

This is the base-name: good.html

2. path.parse(path)

The path.parse() method is used to return an instance whose functionalities signify important elements of the specified path. For Example:

// Importing the 'path' module
const path = require ('path');
// This method returns objects whose properties signify important elements
const myparse = path.parse('D:/node js/ffolder/sfolder/welcome.html');
console.log(myparse);
To execute the above script file, type the following command:
$ node path.js

The Output given as follows:

{
  root: 'D:/',
  dir: 'D:/node js/ffolder/sfolder',
  base: 'welcome.html',
  ext: '.html',
  name: 'welcome'
}

3. path.format(pathObject)

The path.format() method is used to return the string of a path from a specified path instance. This method is the counterpart of path.parse().

For Example:

// Importing the 'path' module
const path = require ('path');
// This method returns a path string
const myformat = path.format({
    dir: 'ffolder\\sfolder\\tfolder',
    base: 'good.html'
});
console.log(myformat);

To execute the above script file, type the following command:

$ node path.js

The Output is given as follows:

 ffolder\sfolder\tfolder\good.html 

4. path.extname(path)

The path.extname() method is used to return the extension of the specified path. It provides the extension of the path starting from the last. (period) to the End of the string in the trailing segment of the path. However, it returns an empty string if no “.” character is present in the basename or if there are no “.” characters other than the first character of the basename of the path provided. For Example:

// Importing the 'path' module
const path = require ('path');
// This method returns the extension of a path
console.log(path.extname('ffolder\\welcome.html'));
console.log(path.extname('hello.js'));
console.log(path.extname('my.world.com'));
console.log(path.extname('.hello'));

To execute the above script file, type the following command:

$ node path.js

The Output is given as follows:

.html
.js 
.com

5. path.dirname(path)

The path.dirname() method is used to return the name of the specified path’s directory. It functions same as the Unix dirname command. For Example:

// Importing the 'path' module
const path = require ('path');
// This method returns the directory name of a path
console.log(path.dirname('ffolder/sfolder/tfolder/good.html'));
To execute the above script file, type the following command:
$ node path.js

The Output should look as follows:

ffolder/sfolder/tfolder

6. path.relative(from, to)

The path.relative() method is used to discover the relative path from one path to another specified, based on the recent functioning directory. However, it will return a zero-length string, if both the input paths are the same. For Example:

// Importing the 'path' module
const path = require ('path');
// This method returns the relative path
console.log(path.relative('ffolder\\sfolder\\tfolder','\\sfolder\\tfolder'));
To execute the above script file, type the following command:
$ node path.js

The Output should look as follows:

..\..\..\..\sfolder\tfolder

7. path.normalize(path)

The path.normalize() method is used to normalize a specified string path. This method can also resolve the segments like ‘..’ and ‘.’ respectively. For Example:

// Importing the 'path' module
const path = require ('path');
// This method normalizes a specified path
const normal = path.normalize('D:\\node js/ffolder\\sfloder/tfolder');
console.log(normal);

To execute the above script file, type the following command:

$ node path.js

The Output should look as follows:

D:\node js\ffolder\sfloder\tfolder

8. path.isAbsolute(path)

The path.isAbsolute() method is used to define whether the specified path is an absolute path or not. If the provided path is a zero-length string, it will return false as an output. For Example:

// Importing the 'path' module
const path = require ('path');
// This method normalizes a specified path
console.log(path.isAbsolute('D:\\node js\\'));
console.log(path.isAbsolute('/node js/'));
console.log(path.isAbsolute('/node js'));
console.log(path.isAbsolute('node js/'));
console.log(path.isAbsolute('.'));

To execute the above script file, type the following command:

$ node path.js

The Output should look as follows:

true
true
true
false
false

9. path.join([…paths])

Thepath.join() method takes two or more segments of a file path and combines them to form a single path with the help of the platform-specific separator as a delimiter. It then normalizes the subsequent path. For Example:

// Importing the 'path' module
const path = require ('path');
// This method is used to join the paths
console.log(path.join('D:\\node js', 'ffolder\\sfolder', 'tfolder\\good.html'));
To execute the above script file, type the following command:
$ node path.js

The Output should look as follows:

D:\node js\ffolder\sfolder\tfolder\good.html

10. path.resolve([…paths])

The path.resolve() method resolves the path's sequence or the segments of the path into an absolute path. This method prepends each subsequent path, processing from right to left until an absolute path is built. For Example:

// Importing the 'path' module
const path = require ('path');
// This method is used to join the paths
console.log(path.resolve('node js', 'ffolder\\sfolder', 'welcome.html'));

To execute the above script file, type the following command:

$ node path.js

The Output should look as follows:

D:\NODE JS\node js\ffolder\sfolder\welcome.html

Related Topics

Node.js Parsing Arguments

Understanding Command-Line Arguments The Strings of text used to transfer extra information to a program through the command-line interface (CLI) while execution of the application, is known as Command-Line arguments. These...

9 minutes read.

Difference Between Node.js and PHP

Node.js vs PHP Node.js and PHP both are the powerful back-ends to create versatile websites. Even when these two technologies fall under the same category, their features are pretty diverse. There's...

6 minutes read.

Node.js Modules

Node.js Modules: At the point when we'll begin composing Node.js applications, we would place all our code into one big node.js file, regardless of how enormous or complex our application...

4 minutes read.

Node.js Callback Concept

Understanding the Concept of Callback A Callback is an asynchronous equivalent for a function that is called at the completion of a task. The Callback helps to avoid any I/O blocking and allows other code to execute...

2 minutes read.

Node.js Console

Node.js Console: Like the JavaScript console mechanism, a console module is designed for Node.js that provides a debugging console for writing or printing messages. Usually, in JavaScript, a console mechanism is...

4 minutes read.

Node.js File System

Introduction to File System in Node.js FS, abbreviated as File System, is a Node.js Build-in Module, which provides an Application Programming Interface (API) to interact with the File System, and to...

15 minutes read.

Node.js Error Handling

Node.js – Error Handling: Errors are part of every programming language, and Node.js Environment is not an exception. There are many predefined errors in Node.js, including errors like SyntaxError, RangeError, and...

4 minutes read.

Node.js OS Module

Introduction to Node.js OS Module The OS Module in Node.js provides the Operating System-related Utilities. This module delivers the functions to interact with the Operating System. It also delivers the Operating...

5 minutes read.

Node.js Event Loop

An Introduction to Event Loop As we have already discussed, Node.js is an Asynchronous platform with a non-blocking I/O. Node.js has awesome features that made it this thriving, and the Event...

5 minutes read.

Difference Between Node.js and Django

Node.js vs Django In Web Application Development, we must have a robust technology to provide strength to our Web application. Node.js and Django both are pretty commanding technologies that help us...

6 minutes read.

Node.js NPM

Node.js – Node Package Manager NPM is an abbreviation for Node Package Manager. It is the default package manager developed by Isaac Z. Schlueter using JavaScript Programming Language, designed for JavaScript Runtime...

7 minutes read.

How to Install Node.js on Windows?

Environment Setup for Node.js Since Node.js is a mandatory section of the program that runs JavaScript, similar to all other required section of programs that run a programming language, it is...

4 minutes read.

Difference Between Nodejs Angular and React

A Right JavaScript Framework Within a business, it is necessary to pick the right technology. As much as this applies to the web application and software development, it also applies in...

5 minutes read.

Node.js Tutorial

Introduction to Node.js: Node.js is a non-proprietary and platform-independent runtime environment for implementing JavaScript code outside of a browser. However, NodeJS isn't a framework and not a programming language. We...

4 minutes read.

Node.js Streams

An Introduction to the Streams Streams are one of the elemental concepts that are introduced to power the applications based on Node.js. These are the method used to handle the data...

6 minutes read.

Node.js Path Module

Understanding the path Module in Node.js The path module is a built-in module of Node.js that provides various methods to interact with the files and directory path names on the device’s...

6 minutes read.

Node.js Events Module

Introduction to the Node.js events Module As we’ve already discussed, Node.js is a JavaScript runtime with an event-driven architecture designed to perform Asynchronous tasks. In order to accomplish the event-driven architecture,...

4 minutes read.

Node.js Discovering Timers

Node.js Discovering Timers: Timers are multi-lingual, and much functional in countless use cases. The Timers are mostly used in many popular programming languages, including Node.js. However, it's pretty simple to...

4 minutes read.

Node.js Event Loop Phases

Node.js – Phases of Event Loop Once we have understood the Node.js event loop concept and the basic introduction to its phases, let's discuss the functions of the Check handler phase...

4 minutes read.

Node.js HTTP Module

An Introduction to HTTP Module The http module is a core module in Node.js that uses the Hypertext Transfer Protocol (HTTP) to transfer data. With the help of the http module,...

7 minutes read.