Skip to content

Instantly share code, notes, and snippets.

@thewei
Forked from dongyuwei/dir2tree.js
Last active August 29, 2015 14:21
Show Gist options
  • Save thewei/75a6e9fa66c51a7d4737 to your computer and use it in GitHub Desktop.
Save thewei/75a6e9fa66c51a7d4737 to your computer and use it in GitHub Desktop.
(function() {
var path = require('path'), fs = require('fs');
function walk(uri,filter,tree) {
var node = {
name : null,
children : [],
pNode : null,
};
if(filter(uri)){
var stat = fs.lstatSync(uri);
if(stat.isFile()){
//转换成绝对路径
uri = path.resolve(uri);
switch(path.extname(uri)){
case '.js':
node.name = uri;
break;
}
}
if(stat.isDirectory()){
node.name = uri;
fs.readdirSync(uri).forEach(function(part){
var n = walk(path.join(uri, part),filter,tree);
if(n.name){
n.pNode = node.name;//增加父节点名称
node.children.push(n);
}
n = null;
});
if(node.name && node.name === tree.name){
tree.children.push(node);
}
}
stat = null;
}
return node;
}
//排除basename以.或者_开头的目录|文件(如.svn,_html,_psd, _a.psd等)
function defaultFilter(uri){
var start = path.basename(uri).charAt(0);
if(start === '.' || start === '_'){
start = null;
return false;
}
return true;
}
/**
* 递归遍历目录文件,获取所有文件路径.
* @param{String}rootDir
* @param{Function}filter:过滤函数,返回false就排除目录|文件
* @return{Object}
* */
module.exports = function(rootDir, filter) {
filter = filter || defaultFilter;
var tree = {
name : rootDir,
children : []
};
walk(rootDir,filter,tree);
return tree.children[0];
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment