billywhizz
12/12/2010 - 4:41 PM

directory walking example

directory walking example

var fs = require("fs");
var util = require("util");

function walkSync(filename, cb) {
	try {
		var stat = fs.lstatSync(filename);
		if(stat.isDirectory()) {
			try {
				if(cb(null, filename, stat)) {
					var files = fs.readdirSync(filename);
					for(var i=0; i<files.length; i++) {
						if(filename == "/") {
							walkSync(filename + files[i], cb);
						}
						else {
							walkSync(filename + "/" + files[i], cb);
						}
					}
				}
			}
			catch(ex) {
				cb(ex);
			}
		}
		else {
			cb(null, filename, stat);
		}
	}
	catch(ex) {
		cb(ex);
	}
}

function walk(filename, cb) {
	fs.lstat(filename, function (err, stat) {
		if(!err) {
			if(stat.isDirectory()) {
				if(cb(null, filename, stat)) {
				    fs.readdir(filename, function(err, files) {
						if(!err) {
							for(var i=0; i<files.length; i++) {
								if(filename == "/") {
									walk(filename + files[i], cb);
								}
								else {
									walk(filename + "/" + files[i], cb);
								}
							}
						}
						else {
							cb(err);
						}
					});
				}
			}
			else {
				cb(null, filename, stat);
			}
		}
		else {
			cb(err, filename);
		}
	});
}

var disallowed = {
	"/media/storage": true,
	"/media/storage2": true,
	"/media/storage3": true,
	"/media/raid1500": true
};

function foo(err, name, stat) {
	if(err) {
		util.debug(err);
		return false;
	}
	//console.log(name);
	return !(name in disallowed);
};

process.argv.forEach(function(val, index, array) {
	if (index > 1) walk(val, foo);
});