This article will show you how to get the file name from an absolute path in Node.js.
When working with file paths in Node.js, it’s a common requirement to extract the file name from an absolute path. While string manipulation operations can achieve this, Node.js provides a more explicit and reliable way to handle file paths through the path
module. In this article, we will explore various methods to obtain the file name from an absolute path in Node.js, taking into consideration scenarios like including or excluding file extensions.
Using path.basename()
The most straightforward approach is to utilize the path.basename()
method, which is specifically designed for extracting the file name from a given path.
Example
const path = require('path'); const absolutePath = '/var/www/foo.txt'; const fileName = path.basename(absolutePath); console.log(fileName);
The path.basename()
function efficiently handles different path separators and returns the last portion of the path, which represents the file name.
Output
foo.txt
Handling File Extensions
If you need to retrieve the file name without its extension, the path.basename()
method allows you to pass an optional second parameter specifying the extension to be removed.
Example
const path = require('path'); const filePath = '/var/www/foo.txt'; const fileNameWithoutExtension = path.basename(filePath, path.extname(filePath)); console.log(fileNameWithoutExtension);
In this example, path.extname(filePath)
returns the extension (including the dot), and then this extension is passed as the second argument to path.basename()
.
This ensures that the file name without the extension is obtained. The resulting fileNameWithoutExtension
will only contain the name part of the file.
Output:
foo
Using path.parse()
Another method provided by the path
module is path.parse()
. This method returns an object containing various components of the path, including the file name, base (file name with extension), and extension.
Example
const path = require('path'); const filePath = 'C:\\Python27\\ArcGIS10.2\\python.exe'; const name = path.parse(filePath).name; console.log(name); // Output: python const base = path.parse(filePath).base; console.log(base); // Output: python.exe const ext = path.parse(filePath).ext; console.log(ext); // Output: .exe
This approach allows you to access different components of the path individually.This approach allows you to access different components of the path individually.