node js get file name without extension
How to Get File Name Without Extension in Node.js
If you are working on a project in Node.js where you need to get the file name without its extension, then you can use the following code:
const path = require('path');
const fileName = path.parse('file.txt').name;
console.log(fileName);
The above code uses the path.parse()
method of the built-in path
module in Node.js. This method takes a file path as an argument and returns an object containing information about the path, such as the directory, base name, and extension.
We can use the name
property of this object to get the file name without the extension.
Another way to achieve the same result is by using the split()
method of the String object:
const fileName = 'file.txt';
const nameWithoutExt = fileName.split('.')[0];
console.log(nameWithoutExt);
In this code, we first define a variable fileName
with the name of the file including its extension. We then use the split()
method to split the file name into an array of strings, using the dot ('.') as the delimiter. The first element of this array contains the file name without the extension.
Both of these methods are equally effective in getting the file name without extension. However, using path.parse()
is recommended because it provides additional information about the file path, which may be useful in certain scenarios.