como-manejar-path-ficheros-nodejs

How to work with file paths in Node.js

  • 2 min

The path module in Node.js provides utilities for handling and transforming file and directory paths in an operating system-independent way.

It is good practice to use these functions instead of manually splitting and concatenating text strings.

Furthermore, being 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 several 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);
Copied!

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
Copied!

Getting a 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
Copied!

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
Copied!

Getting a 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
Copied!

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 relativePath = '../folder1/subfolder/file.txt';
const absolutePath = path.resolve(relativePath);

console.log('Absolute path:', absolutePath);
// Absolute path: C:\..whatever..\folder1\subfolder\file.txt
Copied!

Download the Code

All the code from this post is available for download on Github github-full