Skip to content

Instantly share code, notes, and snippets.

@dongyuwei
Created March 30, 2012 07:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save dongyuwei/2248776 to your computer and use it in GitHub Desktop.
Save dongyuwei/2248776 to your computer and use it in GitHub Desktop.
dir to tree by nodejs 递归遍历目录,生成一个js树对象.
(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