How to find Files by Extension in Node JS?
Today, i will let you know example of node js find all files with extension. In this article, we will implement a node js get file with extension. if you want to see example of node js filter file extensions then you are a right place. let’s discuss about find files by extension node js. Let's see bellow example filter files by extension node js *.html *.jpg *.png *.pdf *.docs.
We will use fs npm package for filter by file extension in folder recursively using node.js. fs package provide readdirSync() and statSync() for search file by extension. let's see simple example
Step 1: Create Node App
run bellow command and create node app.
mkdir my-app
cd my-app
npm init
Step 2: Create server.js file
Make sure, you have add file on "uploads/" folder with some files path.
server.js
var fs = require('fs');
var path = require('path');
function findFileByExt(folderPath, ext)
{
var files = fs.readdirSync(folderPath);
var result = [];
files.forEach(
function (file) {
var newbase = path.join(folderPath,file);
if ( fs.statSync(newbase).isDirectory() ){
result = findFileByExt(newbase,ext,fs.readdirSync(newbase),result);
} else {
if ( file.substr(-1*(ext.length+1)) == '.' + ext ){
result.push(newbase);
}
}
}
)
return result;
}
var folderPath = './uploads';
var files = findFileByExt(folderPath, 'png');
console.log(files);
now you can simply run by following command:
node server.js
Output:
i hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Rename a Folder in Node JS?
- How to Get File Size in Node JS?
- How to Copy File to Another Directory in Node JS?
- Node JS Rename All Files in Folder Example
- How to Rename File in Folder using Node JS?
- How to Delete Directory in Node.js?
- Node JS - How to Delete All Files in Directory?
- How to Check File is Exist or Not in Node JS?
- How to Create Directory if does not Exists in Node JS?
- How to Delete File If Exists in Node JS?
- How to Get All Files from Folder in Node JS?