Languages
[Edit]
EN

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

0 points
Created by:
Dexter
300

In this article, we would like to show you how to get file name with extension from path array 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 names = paths.map(x => path.basename(x));

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

 

Practical example

1. Import path module using:

const path = require('path');

2. Use path.basename() method with the path you want to get the filename from as an argument.

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 = [];

// get file names with extensions
for (const pth of paths) {
    result.push(path.basename(pth));
}

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

Output:

[ 'index.js', 'module1.js', 'module2.js' ]

Note:

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.

❤️💻 🙂

Join