// ---- A parallel loop would look like this: ----
var fs = require('fs');var walk = function(dir, done) {var results = [];fs.readdir(dir, function(err, list) {console.log("list = "+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);}});});});};console.log("process = "+process.env.HOME);
*/
// ------ 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 + "/www/HTML5/nodejs/node_modules/walk", function(err, results) {if (err) throw err;console.log(results);});
沒有留言:
張貼留言