How to use Node.js Path module?

NodeJS has a built-in module that provides a way to work with directories and filenames and also makes it easier to manipulate paths. It has serval functions that help us.

Using the Node.js Path module

To use the path module, we have to require that module

const path = require('path')

We can use various methods, and here are some of the functions:

path.basename(): it returns the trailing part or the last portion of the filename

var filename = path.basename('C:\\Users\\LENOVO\\Desktop\\Paths\\index.html');
console.log(filename);
OUTPUT:
index.html

If we want to avoid the extension of the file and just want to know the name of the file from this long path, we can

let name = path.basename(filename, '.html');
console.log('name of the file:',name );
OUTPUT:
name of the file: index

path.join(): The join method joins two or more parts of a file path into a single string that can be used anywhere a file path is required.

__dirname: is the root directory of the file

const path=require('path')
const photo = 'drum';
let filepath = path.join(__dirname, '/src/images/', photo, '.png');
console.log('the file path of the image is, filepath);
OUTPUT:
the file path of the image is C:\Users\LENOVO\Desktop\Paths\src\images\drum\.png


path.dirname(): method returns the directory name of a path

const path = require('path');
var filepaths=path.dirname('C:\\Users\\LENOVO\\Desktop\\Paths\\index.html')
console.log(filepaths)
OUTPUT:
C:\Users\LENOVO\Desktop\Paths

path.normalize: it normalizes the specified file path. This function takes a path and removes duplicate slashes as well as normalizes directory abbreviations such as ‘.’ for ‘this directory’ and ‘..’ for ‘one level up’ directory.

const path = require('path');
var pathDir=path.normalize('C:\\Users\\LENOVO\\Desktop\\..\\\Paths\\index.html')
console.log(pathDir)
OUTPUT:
C:\Users\LENOVO\Paths\index.html

path.isAbsolute(path): it is a boolean function that returns true if the path specified is absolute. Absolute path refers to the complete details required to locate a file or folder.

const path = require('path');
let res = path.isAbsolute('C:\\Users\\LENOVO\\Desktop\\Paths\\index.html');
console.log(res);
OUTPUT
true
const path = require('path');
let sep = path.isAbsolute('index.html');
console.log(sep);
OUTPUT
false

Leave a Reply

Your email address will not be published. Required fields are marked *