node.js - Nodejs asynchronus callbacks and recursion -


i this

function scan(apath){     var files = fs.readdirsync(apath);     for(var i=0; i<files.length;i++){         var stats = fs.statsync(path.join(apath,files[i]))         if(stats.isdirectory()){             results.push(path.join(apath, files[i]))             scan(path.join(apath,files[i]))         }         if(stats.isfile()){             results.push(path.join(apath,files[i]))         }     } } 

but asynchronously.

trying asynchronous functions led me nightmare this.

function scan(apath){     fs.readdir(apath, function(err, files)){         var counter = files.length;         files.foreach(function(file){             var newpath = path.join(apath, file)             fs.stat(newpath, function(err, stat){                 if(err) return callback(err)                 if(stat.isfile())                     results.push(newpath)                 if(stat.isdirectory()){                     results.push(newpath)                     scan(newpath)                 }                 if(--counter <=0) return              })         })     } } 

all hell breaks loose in node's stack because things don't happen in logical succession in synchronous methods.

you can try async module, , use this:

function scan(apath, callback) {     fs.readdir(apath, function(err, files) {         var counter = 0;         async.whilst(             function() {                 return counter < files.length;             },             function(cb) {                 var file = files[counter++];                 var newpath = path.join(apath, file);                 fs.stat(newpath, function(err, stat) {                     if (err) return cb(err);                     if (stat.isfile()) {                         results.push(newpath);                         cb(); // asynchronously call loop                     }                     if (stat.isdirectory()) {                         results.push(newpath);                         scan(newpath, cb); // recursion loop                     }                 });             },             function(err) {                 callback(err); // loop over, come out             }         );     }); } 

look more async.whilst


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -