0
0
Node.jsframework~5 mins

path.basename and path.dirname in Node.js

Choose your learning style9 modes available
Introduction

These functions help you get parts of a file path easily. basename gets the file name, and dirname gets the folder path.

When you want to get just the file name from a full file path.
When you need to find the folder containing a file.
When organizing files and you want to separate folder names from file names.
Syntax
Node.js
const path = require('path');

path.basename(pathString[, ext])
path.dirname(pathString)

pathString is the full path you want to work with.

ext in basename is optional and removes the file extension if given.

Examples
Gets the file name file.txt from the full path.
Node.js
const path = require('path');

const fileName = path.basename('/home/user/docs/file.txt');
console.log(fileName);
Gets the folder path /home/user/docs from the full path.
Node.js
const path = require('path');

const folder = path.dirname('/home/user/docs/file.txt');
console.log(folder);
Gets the file name without extension: file.
Node.js
const path = require('path');

const fileNameNoExt = path.basename('/home/user/docs/file.txt', '.txt');
console.log(fileNameNoExt);
Sample Program

This program shows how to get the file name, folder path, and file name without extension from a full file path.

Node.js
const path = require('path');

const fullPath = '/users/alex/projects/app/index.js';

const fileName = path.basename(fullPath);
const folderName = path.dirname(fullPath);
const fileNameNoExt = path.basename(fullPath, '.js');

console.log('File name:', fileName);
console.log('Folder path:', folderName);
console.log('File name without extension:', fileNameNoExt);
OutputSuccess
Important Notes

These functions work with both Windows and Unix-style paths.

Use basename with the extension argument to remove file extensions easily.

Summary

path.basename gets the file name from a full path.

path.dirname gets the folder path from a full path.

They help split paths into useful parts for file handling.