Created
May 15, 2013 08:48
-
-
Save ibigbug/5582527 to your computer and use it in GitHub Desktop.
node-walk
This file contains 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
var fs = require('fs'), | |
path = require('path'); | |
exports.walk = function(abspath, callback){ | |
/* | |
* callback will get { dirname: {file1: file1_abs_path, subdir: { fil2: file2_abs_path, subdir2: {}.. }}; | |
* if not callback passed, it just returns a tree like above; | |
*/ | |
var dir_tree = {}, | |
dirname = path.resolve(abspath).split(path.sep).pop(); | |
dir_tree[dirname] = {}; | |
(function wrapper(dirpath, ret){ | |
fs.readdirSync(dirpath).forEach(function(item){ | |
if (fs.statSync(path.join(dirpath, item)).isDirectory()) { | |
var subdir = ret[item] = {}; | |
wrapper(path.join(dirpath, item), subdir); | |
} else { | |
ret[item] = path.join(abspath, item); | |
} | |
}); | |
})(abspath, dir_tree[dirname]); | |
if (callback) return callback(dir_tree); | |
return dir_tree; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment