0
0
NodejsHow-ToBeginner · 3 min read

How to Use path.basename in Node.js: Simple Guide

In Node.js, use path.basename(path, ext) to get the last part of a file path, usually the file name. The optional ext argument removes a file extension if it matches. This method helps extract file names from full paths easily.
📐

Syntax

The path.basename method takes two arguments:

  • path: A string representing the full file path.
  • ext (optional): A string for the file extension to remove from the result.

It returns the last portion of the path, typically the file name.

javascript
const path = require('path');

path.basename(pathString[, ext])
💻

Example

This example shows how to get the file name from a full path and how to remove the extension if needed.

javascript
const path = require('path');

const fullPath = '/home/user/docs/letter.txt';

// Get file name with extension
const fileName = path.basename(fullPath);
console.log(fileName); // Outputs: letter.txt

// Get file name without extension
const fileNameNoExt = path.basename(fullPath, '.txt');
console.log(fileNameNoExt); // Outputs: letter
Output
letter.txt letter
⚠️

Common Pitfalls

Common mistakes include:

  • Not importing the path module before using basename.
  • Passing a wrong or empty path string, which returns an empty string.
  • Using the ext argument incorrectly, such as omitting the dot . in the extension.

Always ensure the extension string starts with a dot when using the second argument.

javascript
const path = require('path');

// Wrong: missing dot in extension
const wrongExt = path.basename('/file/example.txt', 'txt');
console.log(wrongExt); // Outputs: example.txt (extension not removed)

// Correct: include dot
const correctExt = path.basename('/file/example.txt', '.txt');
console.log(correctExt); // Outputs: example
Output
example.txt example
📊

Quick Reference

ParameterDescriptionExample
pathFull file path string'/folder/file.txt'
ext (optional)Extension to remove (include dot)'.txt'
ReturnLast part of path, file name'file.txt' or 'file' if ext removed

Key Takeaways

Use path.basename(path) to get the file name from a full path string.
Pass the file extension with a leading dot as the second argument to remove it.
Always import the path module before using path.basename.
If the extension argument is incorrect or missing the dot, it won't remove the extension.
An empty or invalid path returns an empty string.