Node.js - get file names without extensions from array of paths

0 points
Created by:

In this article, we would like to show you how to get file name without extension from path in Node.js.

Quick solution:

const path = require('path');

// example array of paths
const paths = ['C:/app/index.js', 'C:/app/module1.js', 'C:/app/module2.js'];

const result = => {
    const extension = path.extname(pth);  // get file extension
    return path.basename(pth, extension); // for each pth return only file name


Practical example

1. Import path module using:

const path = require('path');

2. For each path in the array:

  1. Use path.extname() method with the path you want to get the filename from as an argument to get the file extension. We need to know the file extension, so we can get rid of it in the next step.
  2. Use path.basename() method with the path and the optional extension argument so the file extension will be removed leaving only the file name.
  3. Push the name to the result array.

Practical example:

const path = require('path');

// example array of paths
const paths = ['C:/app/index.js', 'C:/app/module1.js', 'C:/app/module2.js'];
const result = [];

for (const pth of paths) {
    // get file extension
    const extension = path.extname(pth);

    // push file name without extension to the result array
    result.push(path.basename(pth, extension));

console.log(result); // [ 'index', 'module1', 'module2' ]


[ 'index', 'module1', 'module2' ]


The path.basename() method with one argument (myPath) returns file name with extension from given path.


In this solution we used for...of loop to iterate through the paths array, but you can use any other method from the following article:

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂