The path
module of Node.js provides utilities to handle and transform file and directory paths independently of the operating system.
It is a good practice to use these functions, instead of manually splitting and concatenating strings.
Also, being independent of the operating system, your code will work correctly on different operating systems, such as Windows, macOS, and Linux.
Path Module Functions
Let’s take a 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 various parts of a path into a single complete path.
import path from 'node:path';
const ruta1 = '/folder1';
const ruta2 = 'subfolder/file.txt';
const rutaCompleta = path.join(ruta1, ruta2);
console.log('Complete path:', rutaCompleta);
Normalizing a Path
Path normalization is important to eliminate redundancies and simplify paths. The normalize
function of the path
module allows you to do this easily.
import path from 'node:path';
const ruta = '/folder1//subfolder/./file.txt';
const rutaNormalizada = path.normalize(ruta);
console.log('Normalized path:', rutaNormalizada);
// 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 ruta = '/folder1/subfolder/file.txt';
const nombreBase = path.basename(ruta);
console.log('File name:', nombreBase);
// 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 ruta = '/folder1/subfolder/file.txt';
const nombreDirectorio = path.dirname(ruta);
console.log('Directory name:', nombreDirectorio);
// Directory name: /folder1/subfolder
Getting the File Extension
With the extname
function, you can get the file extension from a given path.
import path from 'node:path';
const ruta = '/folder1/subfolder/file.txt';
const extension = path.extname(ruta);
console.log('File extension:', extension);
// File extension: .txt
Converting a Relative Path to an Absolute Path
To convert a relative path to an absolute path, you can use the resolve
function.
import path from 'node:path';
const rutaRelativa = '../folder1/subfolder/file.txt';
const rutaAbsoluta = path.resolve(rutaRelativa);
console.log('Absolute path:', rutaAbsoluta);
// Absolute path: C:\..whatever..\folder1\subfolder\file.txt