any ideas on async directory search using fs.readdir? realise introduce recursion , call read directory function next directory read, little worried not being async...
any ideas? i've looked @ node-walk great, doesn't give me files in array, readdir does. although
looking output like...
['file1.txt', 'file2.txt', 'dir/file3.txt']
there 2 ways of accomplishing this. in async environment you'll notice there 2 kinds of loops: serial , parallel. serial loop waits 1 iteration complete before moves onto next iteration - guarantees every iteration of loop completes in order. in parallel loop, iterations started @ same time, , 1 may complete before another, however, faster serial loop. in case, it's better use parallel loop because doesn't matter order walk completes in, long completes , returns results (unless want them in order).
a parallel loop this:
var fs = require('fs'); var path = require('path'); 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 = path.resolve(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 this:
var fs = require('fs'); var walk = function(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var = 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(); } }); })(); }); };
and test out on home directory (warning: results list huge if have lot of stuff in home directory):
walk(process.env.home, function(err, results) { if (err) throw err; console.log(results); });
edit: improved examples.
Comments
Post a Comment