node.js fs.readdir recursive directory search

node.js fs.readdir recursive directory search

A parallel loop would look like this:

var fs = require('fs');
var walk =function(dir, done){
  var results =[];
  fs.readdir(dir,function(err, list){
    if(err)return done(err);
    var pending = list.length;
    if(!pending)return done(null, results);
    list.forEach(function(file){
      file = dir +'/'+ file;
      fs.stat(file,function(err, stat){
        if(stat && stat.isDirectory()){
          walk(file,function(err, res){
            results = results.concat(res);
            if(!--pending) done(null, results);
          });
        }else{
          results.push(file);
          if(!--pending) done(null, results);
        }
      });
    });
  });
};

A serial loop would look like this:

var fs = require('fs');
var walk =function(dir, done){
  var results =[];
  fs.readdir(dir,function(err, list){
    if(err)return done(err);
    var i =0;
    (function next(){
      var file = list[i++];
      if(!file)return done(null, results);
      file = dir +'/'+ file;
      fs.stat(file,function(err, stat){
        if(stat && stat.isDirectory()){
          walk(file,function(err, res){
            results = results.concat(res);
            next();
          });
        }else{
          results.push(file);
          next();
        }
      });
    })();
  });
};
walk(process.env.HOME,function(err, results){
  if(err)throw err;
  console.log(results);
});

Have a look at the file module. It has a function called walk:

file.walk(start, callback)

Navigates a file tree, calling callback for each directory, passing in (null, dirPath, dirs, files).

unix find 

var execFile = require('child_process').execFile;
execFile('find',['somepath/'],function(err, stdout, stderr){
  var file_list = stdout.split('\n');
  /* now you've got a list with full path file names */
}

 npm package, wrench

var wrench = require("wrench");

var files = wrench.readdirSyncRecursive("directory");

wrench.readdirRecursive("directory",function(error, files){
    // live your dreams
});

 

 npm package is glob.

npm install glob

readdirp.

documentation 

npm install readdirp

 

 

 

 

 

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s