我循环遍历目录结构,似乎readdirSync()按字母顺序返回所有内容。有没有办法让我通过文件夹/文件然后按字母顺序获取?由于我正在重新创建文件夹结构,我现在最终将文件夹和文件混合在一起,而不是按字母顺序首先对所有文件夹进行分组,然后按字母顺序对所有文件进行分组,这是我更喜欢的。
function buildProjectStructure(currentPath, root){
var files = fs.readdirSync(currentPath);
for(var i in files){
var currentFile = currentPath + "/" + files[i];
var stats = fs.statSync(currentFile);
if(stats.isFile()){
// todo: add file to tree view
root.append("<li>" + files[i] + "</li>")
}
else if(stats.isDirectory()){
// todo: add folder to tree view
var folder = $("<li><input type='checkbox' id='" + files[i] + "' /><label for='" + files[i] + "'>" + files[i] + "</label>").appendTo(root)
var folderUL = $("<ul/>").appendTo(folder);
buildProjectStructure(currentFile, folderUL);
}
}
}
答案 0 :(得分:0)
所以我从readdirSync()获取后将文件/文件夹分成两个列表,然后将两个列表合并。
function getOrderedFoldersFiles(currentPath, files){
var _folders = [];
var _files = [];
for(var i in files){
var currentFile = currentPath + "/" + files[i];
var stats = fs.statSync(currentFile);
if(stats.isFile()){
_files.push(files[i]);
}
else if(stats.isDirectory()){
_folders.push(files[i]);
}
}
return _folders.concat(_files);
}
function buildProjectStructure(currentPath, root){
var files = fs.readdirSync(currentPath);
var _files = getOrderedFoldersFiles(currentPath, files);
for(var i in _files){
var currentFile = currentPath + "/" + _files[i];
var stats = fs.statSync(currentFile);
//alert(currentFile);
if(stats.isFile()){
// todo: add file to tree view
root.append("<li>" + _files[i] + "</li>")
}
else if(stats.isDirectory()){
// todo: add folder to tree view
var folder = $("<li><input type='checkbox' id='" + _files[i] + "' /><label for='" + _files[i] + "'>" + _files[i] + "</label>").appendTo(root)
var folderUL = $("<ul/>").appendTo(folder);
buildProjectStructure(currentFile, folderUL);
}
}
}