Skip to content

Instantly share code, notes, and snippets.

@ibigbug
Created May 15, 2013 08:48
Show Gist options
  • Save ibigbug/5582527 to your computer and use it in GitHub Desktop.
Save ibigbug/5582527 to your computer and use it in GitHub Desktop.
node-walk
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