我有这个Google驱动器脚本,我想使用它来获取特定驱动器的所有文件和子文件夹的列表。
我有基本代码,但问题是它不是按名称排序,而是基于最后修改的文件。我该如何更改?
var childFolders = parent.getFolders();
这是我找到的代码,但有一些修改。我不确定如何在此处合并排序:
/* Change the FOLDER NAME to generate tree for any specify folder */
function generateFolderTree() {
var docu = DocumentApp.create('Document');
// If you want a tree of any sub folder
var parentFolder = DriveApp.getFoldersByName("Folder name").next();
// If you want to search from the top (root) folder
//var parentFolder = DriveApp.getRootFolder();
getChildFolders(parentFolder,docu);
}
function getChildFolders(parent,docu) {
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
var childFolder_name = childFolder.getName();
docu.appendParagraph(childFolder_name);
var files = childFolder.getFiles();
while (files.hasNext()) {
var files_name = files.next().getName();
docu.appendListItem(files_name);
}
// Recursive call for any sub-folders
getChildFolders(childFolder,docu);
}
}
一种简单的解决方案是将getChildFolders()
函数替换为以下内容:
function getChildFolders(parent, docu) {
var childFolders = getSorted(parent.getFolders());
for (var i=0; i<childFolders.length; i++) {
var childFolder = childFolders[i];
var childFolder_name = childFolder.getName();
docu.appendParagraph(childFolder_name);
var files = getSorted(childFolder.getFiles());
for (var j=0; j<files.length; j++) {
var files_name = files[j].getName();
docu.appendListItem(files_name);
}
// Recursive call for any sub-folders
getChildFolders(childFolder,docu);
}
}
function getSorted(it) {
var l = [];
while (it.hasNext()) {
var f = it.next();
l.push(f);
}
return l.sort(function(a, b) {
if (a.getName() < b.getName()) {
return -1;
}
if (a.getName() > b.getName()) {
return 1;
}
return 0;
});
}
想法是,在获得子文件夹/文件后,立即使用getSorted(it)
功能在辅助功能Array.prototype.sort()中对其进行排序。
或者,您可以使用API的orderBy
方法的Files: list参数。