Nik Hendricks
Nik Hendricks

Reputation: 294

Listing Dirs, sub-dirs and its files using node js and fs

So I am trying to make a simple function that will list all the files and folders in a set directory in my case the files are 'attack modules' but anyways I have got the function below to work a little bit but it will crash if there is any subfolder with files in it

function getAttackModuleFiles(where, name, parentFolder){
  var parentFolder = parentFolder
  console.log('p1 '+parentFolder)
  sub++

  var path = 'adminPanel/attackModules/'
  fs.readdir(where, (err, files) => {
    if(err){
      console.log(err)
    }
    files.forEach(name => {
      console.log(sub)
      var stats = fs.statSync(where+name);
        if(stats.isFile() == true){
          var dir = path+parentFolder+'/'+name
          socket.emit('attackModule','file',name, parentFolder, sub, dir)
        }if(stats.isDirectory() == true){

            /*
            if(sub == 2){

            getAttackModuleFiles(path+name+'/',name, name)
            //getAttackModuleFiles(path+parentFolder+'/'+name+'/',name, parentFolder)
            socket.emit('attackModule','dir',name, name, sub)

          }else
           if( sub ==1){
           */

          getAttackModuleFiles(path+name+'/',name, name)
          console.log(name)
          socket.emit('attackModule','dir',name, name, sub)
         // }
        }
     });
  })
}

I do not yet have enough knowledge of js to know how to solve this can someone help me figure out how to be able to keep listing files and folders infinitely

Upvotes: 0

Views: 71

Answers (1)

Akhilesh krishnan
Akhilesh krishnan

Reputation: 799

There is much easier way of using the Walker module, the advantage with this is

  1. It walks through the file and folders recursively and we need not loop at all.
  2. It emits various events which can be listened to for instance events like finding a directory, finding a file, finding symbolic links, on error etc..

    var walker    = require('walker');
    
    if (process.argv.length <= 2) {
        console.log("Usage: " + __filename + " path/to/directory");
        process.exit(-1);
    }
    
    var path = process.argv[2];
    
    walker(path)
        .on('dir', function(dir, stat) {
            console.log('Got directory: ' + dir)
        })
        .on('file', function(file, stat) {
            console.log('Got file: ' + file)
        })
        .on('end', function() {
            console.log('All files traversed.')
        });
    

pass the directory path as a parameter while executing node like node index.js testDir/

Upvotes: 1

Related Questions