-
-
Save 19h/6187951 to your computer and use it in GitHub Desktop.
Recursive directory walker / indexer / lister with array, object-stat hashmap and joint-mode support. For V8/Node.js, in Javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
__ ___ | |
/\ \ __ /'___\ | |
\ \ \ __ __ /\_\/\ \__/ __ __ | |
\ \ \ __ /'__`\ /'_ `\/\ \ \ ,__\/\ \/\ \ | |
\ \ \L\ \/\ __//\ \L\ \ \ \ \ \_/\ \ \_\ \ | |
\ \____/\ \____\ \____ \ \_\ \_\ \/`____ \ | |
\/___/ \/____/\/___L\ \/_/\/_/ `/___/> \ | |
/\____/ /\___/ | |
\_/__/ \/__/ | |
Copyright (c) 2013 by Legify UG. All Rights Reserved. | |
This is our signature | |
And it means everything. | |
*/ | |
/* | |
PRIMARY | |
ctype & | |
001 - Array [& ] | |
010 - Object-Stat Hashmap | |
EXAMPLE | |
readDictionary("./static", 1, console.log) | |
will yield an array | |
readDictionary("./static", 2, console.log) | |
will yield an object-stat hashmap | |
readDictionary("./static", 3, console.log) | |
will yield both an array and an object-stat hashmap | |
*/ | |
var readDictionary = function (start, ctype, callback) { | |
var readDir, stash = {}; | |
ctype instanceof Function && ( callback = ctype, ctype = 1 ); | |
return (readDir = function(start, callback) { | |
fs.lstat(start, function(err, stat) { | |
if (err) return callback(err); | |
var found = { dirs: [], files: [] }, | |
total = 0, processed = 0; | |
if (stat.isDirectory()) { | |
fs.readdir(start, function(err, files) { | |
total = files.length; | |
if (!total) | |
return callback(null, found, total); | |
files.forEach(function (a) { | |
var abspath = path.join(start, a); | |
fs.stat(abspath, function(err, stat) { | |
if (stat.isDirectory()) { | |
ctype & 1 && found.dirs.push(abspath); | |
ctype & 2 && (stash[abspath] = stat); | |
readDir(abspath, function(err, data) { | |
if ( ctype & 1 ) { | |
found.dirs = found.dirs.concat(data.dirs); | |
found.files = found.files.concat(data.files); | |
} | |
(++processed == total) && callback(null, found, stash); | |
}); | |
} else { | |
ctype & 1 && found.files.push(abspath); | |
ctype & 2 && (stash[abspath] = stat); | |
(++processed == total) && callback(null, found, stash); | |
} | |
}); | |
}) | |
}); | |
} else { | |
return false; | |
} | |
}); | |
})(start, function (a, b, c) { | |
if ( !(ctype ^ 3) ) | |
return callback(b, c); | |
if ( ctype & 1 ) | |
return callback(b); | |
if ( ctype & 2 ) | |
return callback(c); | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Friends, did you mean having
var path = require('path')
in the upper scope?