Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find files by extension, *.html under a folder in nodejs

I'd like to find all *.html files in src folder and all its sub folders using nodejs. What is the best way to do it?

var folder = '/project1/src'; var extension = 'html'; var cb = function(err, results) {    // results is an array of the files with path relative to the folder    console.log(results);  } // This function is what I am looking for. It has to recursively traverse all sub folders.  findFiles(folder, extension, cb); 

I think a lot developers should have great and tested solution and it is better to use it than writing one myself.

like image 755
Nicolas S.Xu Avatar asked Aug 23 '14 09:08

Nicolas S.Xu


People also ask

How do I read a folder in node JS?

Use fs. readdir() or fs. readdirSync() or fsPromises. readdir() to read the contents of a directory.


1 Answers

node.js, recursive simple function:

var path = require('path'), fs=require('fs');  function fromDir(startPath,filter){      //console.log('Starting from dir '+startPath+'/');      if (!fs.existsSync(startPath)){         console.log("no dir ",startPath);         return;     }      var files=fs.readdirSync(startPath);     for(var i=0;i<files.length;i++){         var filename=path.join(startPath,files[i]);         var stat = fs.lstatSync(filename);         if (stat.isDirectory()){             fromDir(filename,filter); //recurse         }         else if (filename.indexOf(filter)>=0) {             console.log('-- found: ',filename);         };     }; };  fromDir('../LiteScript','.html'); 

add RegExp if you want to get fancy, and a callback to make it generic.

var path = require('path'), fs=require('fs');  function fromDir(startPath,filter,callback){      //console.log('Starting from dir '+startPath+'/');      if (!fs.existsSync(startPath)){         console.log("no dir ",startPath);         return;     }      var files=fs.readdirSync(startPath);     for(var i=0;i<files.length;i++){         var filename=path.join(startPath,files[i]);         var stat = fs.lstatSync(filename);         if (stat.isDirectory()){             fromDir(filename,filter,callback); //recurse         }         else if (filter.test(filename)) callback(filename);     }; };  fromDir('../LiteScript',/\.html$/,function(filename){     console.log('-- found: ',filename); }); 
like image 178
Lucio M. Tato Avatar answered Sep 19 '22 15:09

Lucio M. Tato