The path
module in Node.js provides utilities for handling and transforming file and directory paths in a way that is independent of the operating system.
It is a good practice to use these functions instead of manually splitting and concatenating strings.
Additionally, because they are operating system independent, your code will work correctly on different operating systems, such as Windows, macOS, and Linux.
Functions of the Path Module
Let’s look at some of the most important functions of the path
module, along with practical examples of how to use them.
Joining Paths
The join
function of the path
module is used to join multiple parts of a path into a single complete path.
import path from 'node:path';
const path1 = '/folder1';
const path2 = 'subfolder/file.txt';
const completePath = path.join(path1, path2);
console.log('Complete path:', completePath);
Normalizing a Path
Path normalization is important for removing redundancies and simplifying paths. The normalize
function of the path
module allows you to do this easily.
import path from 'node:path';
const path = '/folder1//subfolder/./file.txt';
const normalizedPath = path.normalize(path);
console.log('Normalized path:', normalizedPath);
// Normalized path: \folder1\subfolder\file.txt
Getting the File Name
The basename
function allows you to get the base name of a file from a given path.
import path from 'node:path';
const path = '/folder1/subfolder/file.txt';
const baseName = path.basename(path);
console.log('File name:', baseName);
//File name: file.txt
Getting the Directory Name
To get the directory name from a given path, you can use the dirname
function.
import path from 'node:path';
const path = '/folder1/subfolder/file.txt';
const directoryName = path.dirname(path);
console.log('Directory name:', directoryName);
//Directory name: /folder1/subfolder
Getting the File Extension
With the extname
function, you can get the extension of a file from a given path.
import path from 'node:path';
const path = '/folder1/subfolder/file.txt';
const extension = path.extname(path);
console.log('File extension:', extension);
// File extension: .txt
Converting a Relative Path to Absolute
To convert a relative path to an absolute path, you can use the resolve
function.
import path from 'node:path';
const relativePath = '../folder1/subfolder/file.txt';
const absolutePath = path.resolve(relativePath);
console.log('Absolute path:', absolutePath);
// Absolute path: C:\..whatever..\folder1\subfolder\file.txt
Download the Code
All the code from this entry is available for download on Github