Skip to content
the poor coder

node js get file name without extension

Poor Man
Published
Reading time
1 min read

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC