soldair / node-walkdir

Walk a directory tree emitting events based on the contents. API compatable with node-findit. Walk a tree of any depth. Fast! Handles permission errors. Stoppable. windows support. Pull requests are awesome. watchers are appreciated.
MIT License
130 stars 22 forks source link

Async Problems #30

Closed Thukyd closed 7 years ago

Thukyd commented 7 years ago

Hey,

I am quite new to Node and have slight trouble to use your module async. I tried to get help in books and stackoverflow, but I don't know how to deal with "walk".

What i would like to do is to fill an array with data (which comes with the help of walkdir) and return after the walkdir is finished and the data is processed.


var myThing = (parameter ) => {
  // should be filled
  var data = [];

  walk(directory, function(path, stat) {
   [...]
     // look at a file, process it and eventually push into "data"
    data.push({"path" : path, [...] });
   [...]
  });

  // after "walk" finished, the filled "data" should be returned
  return data;
}
soldair commented 7 years ago

hey. welcome!

it totally makes sense you are having isues here. This module is quite old and has gathered a few idiosyncrasies of it's own

walk(directory, function(path, stat) { // do stuff }).on('end',function(){ // im all done! })

also if you use async functionc in javascript you can't use return. (you can if you use a version of node that aupports async/wait but thats a whole nother js lesson)

so you'll have to write myThing a little differently.

var myThing = function(directory,callback){
 var data =[]
 walk(directory, function(path, stat) {
    // do stuff
   data.push({"path" : path,stat:stat });
  }).on('end',function(){
    // im all done!
    callback(false,data)
  }).on('error',function(err){
    callback(err)
  })
}

now when you want to call myThing you get the result from the callback

myThing('/',function(err,paths){
  if(err) console.log('there was an error ',err)
  console.log('all done got paths ',paths)
})
Thukyd commented 7 years ago

Wow, thank you so much for taking the time and explaining it so well. I will try it out!