EN
Node.js - get file names with extensions from array of paths
0 points
In this article, we would like to show you how to get file name with extension from path array in Node.js.
Quick solution:
xxxxxxxxxx
1
const path = require('path');
2
3
// example array of paths
4
const paths = ['C:/app/index.js', 'C:/app/module1.js', 'C:/app/module2.js'];
5
const names = paths.map(x => path.basename(x));
6
7
console.log(names); // [ 'index.js', 'module1.js', 'module2.js' ]
1. Import path
module using:
xxxxxxxxxx
1
const path = require('path');
2. Use path.basename()
method with the path you want to get the filename from as an argument.
Practical example:
xxxxxxxxxx
1
const path = require('path');
2
3
// example array of paths
4
const paths = ['C:/app/index.js', 'C:/app/module1.js', 'C:/app/module2.js'];
5
6
const result = [];
7
8
// get file names with extensions
9
for (const pth of paths) {
10
result.push(path.basename(pth));
11
}
12
13
console.log(result); // [ 'index.js', 'module1.js', 'module2.js' ]
Output:
xxxxxxxxxx
1
[ 'index.js', 'module1.js', 'module2.js' ]
Note:
In this solution we used
for...of
loop to iterate through thepaths
array, but you can use any other method from the following article: