The path.basename() method in Node.js is part of the Path module and is used to extract the last portion of a file path. It returns the file or directory name from a given path and can optionally remove a specified file extension from the result. This method is useful when working with file paths and filenames across different operating systems.
- Extracts the filename from a complete file path.
- Can remove a specified file extension from the returned filename.
- Works with both absolute and relative paths.
- Commonly used in file management, logging, and upload-related applications.
Syntax
path.basename(path[, suffix])where,
- path: The file path from which the basename is extracted.
- suffix (optional): A file extension to remove from the returned basename.
Return Value: It returns a string with the filename portion of the path. It throws an error if the path or the extension parameters are not string values.
Example 1: Using UNIX file paths
// Node.js program to demonstrate the
// path.basename() method
// Import the path module
const path = require('path');
path1 = path.basename('/home/user/bash/index.txt');
console.log(path1)
// Using the extension parameter
path2 = path.basename('/home/user/bash/index.txt', '.txt');
console.log(path2)
Output:
index.txt
index
Example 2: Using Windows file paths
// Node.js program to demonstrate the
// path.basename() method
// Import the path module
const path = require('path');
path1 = path.basename('C:\\users\\bash\\index.html');
console.log(path1)
// Using the extension parameter
path2 = path.basename('C:\\users\\bash\\index.html', '.html');
console.log(path2)
Output:
index.html
index
Use Cases of path.basename() Method
- Extracting filenames: Retrieves the file name from a complete file path without including the directory structure.
- Removing file extensions: Returns the file name without a specified extension when the optional suffix parameter is provided.
- Handling uploaded files: Helps display or store only the file name instead of the full path supplied during upload.
- Generating cleaner logs and reports: Makes log entries and error messages easier to read by showing only the file name.
- File processing and automation: Simplifies tasks that require working with file names while ignoring their parent directories.