从具有多个级别的文件夹中获取子文件夹

时间:2015-09-02 08:16:12

标签: javascript directory subdirectory

我有代码检查文件夹子文件夹中的所有文件。但是我如何才能将其更改为不仅检查子文件夹级别,还检查子文件夹的子文件夹等等?

这是我对该文件夹及其子文件夹的代码:

            var fso = new ActiveXObject("Scripting.FileSystemObject");
            fso = fso.getFolder(path);
            var subfolders = new Object();
            subfolders = fso.SubFolders;
            var oEnumerator = new Enumerator(subfolders);
            for (;!oEnumerator.atEnd(); oEnumerator.moveNext())
            {
                var itemsFolder = oEnumerator.item().Files;
                var oEnumerator2 = new Enumerator(itemsFolder);
                var clientFileName = null;

                for(;!oEnumerator2.atEnd(); oEnumerator2.moveNext())
                {
                    var item = oEnumerator2.item();
                    var itemName = item.Name;
                    var checkFile = itemName.substring(itemName.length - 3);
                    if(checkFile == ".ac")
                    {
                        var clientFileName = itemName;
                        break;
                    }
                }
            }

在每个级别的子文件夹上,我需要检查所有文件是否可以找到.ac文件。

2 个答案:

答案 0 :(得分:0)

我在评论中提到的解决方案看起来像这样(我对ActiveX不太了解,因此有很多评论,所以希望你可以轻松纠正任何错误):

//this is the function that looks for the file inside a folder.
//if it's not there, it looks in every sub-folder by calling itself
function getClientFileName(folder) {
    //get all the files in this folder
    var files = folder.Files;
    //create an enumerator to check all the files
    var enumerator = new Enumerator(files);
    for(;!enumerator.atEnd(); enumerator.moveNext()) {
        //get the file name we're about to check
        var file = enumerator.item().Name;
        //if the file name is too short skip this one
        if (file.length<3) continue;
        //check if this file's name matches, if it does, return it
        if (file.substring(file.length - 3)==".ac") return file;
    }
    //if we finished this loop, then the file was not inside the folder
    //so we check all the sub folders
    var subFolders = folder.SubFolders;
    //create an enumerator to check all sub folders
    enumerator = new Enumerator(subFolders);
    for(;!enumerator.atEnd(); enumerator.moveNext()) {
        //get the sub folder we're about to check
        var subFolder = enumerator.item();
        //try to find the file in this sub folder
        var fileName = getClientFileName(subFolder);
        //if it was inside the sub folder, return it right away
        if (fileName!=null) return fileName;
    }
    //if we get this far, we did not find the file in this folder
    return null;
}

然后你会像这样调用这个函数:

var theFileYouAreLookingFor = getClientFileName(theFolderYouWantToStartLookingIn);

再一次,要注意上面的代码:我没有测试它,也不了解ActiveX,我只是拿了你的代码并改了它,所以它应该查看所有的子文件夹。

答案 1 :(得分:0)

你想要的是一个递归函数。这是一个简单的递归函数,它通过提供的路径中的每个文件进行迭代,然后进行递归调用以通过每个子文件夹文件进行迭代。对于遇到的每个文件,此函数调用提供的回调(您可以在其中执行任何处理逻辑)。

功能:

function iterateFiles(path, recursive, actionPerFileCallback){ 
    var fso = new ActiveXObject("Scripting.FileSystemObject"); 
    //Get current folder
    folderObj = fso.GetFolder(path);

    //Iterate thru files in thisFolder
    for(var fileEnum = new Enumerator(folderObj.Files); !fileEnum.atEnd(); fileEnum.moveNext()){
      //Get current file
      var fileObj = fso.GetFile(fileEnum.item());

      //Invoke provided perFile callback and pass the current file object
      actionPerFileCallback(fileObj);
    }

    //Recurse thru subfolders
    if(recursive){
      //Step into each sub folder
      for(var subFolderEnum = new Enumerator(folderObj.SubFolders); !subFolderEnum.atEnd(); subFolderEnum.moveNext()){
          var subFolderObj = fso.GetFolder(subFolderEnum.item());

          //Make recursive call
          iterateFiles(subFolderObj.Path, true, actionPerFileCallback);
        }   
    }
};

用法(这里我传入一个匿名函数,为每个文件调用):

iterateFiles(pathToFolder, true, function(fileObj){
    Wscript.Echo("File Name: " + fileObj.Name); 
};

现在..这是一个非常基本的例子。下面是一个类似功能的更复杂的实现。在这个函数中,我们可以像以前一样递归地遍历每个文件。但是,现在调用者可以向函数提供“调用上下文”,该调用上下文又被传递回回调。这可能很强大,因为现在调用者可以使用它自己的闭包中的先前信息。另外,我为调用者提供了在每个递归级别更新调用上下文的机会。在设计此函数时,为了满足我的特定需求,有必要提供检查每个回调函数是否成功的选项。所以,你会在这个函数中看到对它的检查。我还包括为遇到的每个文件夹执行回调的选项。

更复杂的功能:

function iterateFiles(path, recursive, actionPerFileCallback, actionPerFolderCallback, useFnReturnValue, callingContext, updateContextFn){ 
    var fso = new ActiveXObject("Scripting.FileSystemObject"); 
    //If 'useFnReturnValue' is true, then iterateFiles() should return false IFF a callback fails. 
    //This function simply tests that case.
    var failOnCallbackResult = function(cbResult){
        return !cbResult && useFnReturnValue;
    }

    //Context that is passed to each callback
    var context = {};

    //Handle inputs
    if(callingContext != null){
        context.callingContext = callingContext;
    }

    //Get current folder
    context.folderObj = fso.GetFolder(path);

    //Do actionPerFolder callback if provided
    if(actionPerFolderCallback != null){
        var cbResult = Boolean(actionPerFolderCallback(context));
        if (failOnCallbackResult(cbResult)){
            return false;
        }
    }

    //Iterate thru files in thisFolder
    for(var fileEnum = new Enumerator(context.folderObj.Files); !fileEnum.atEnd(); fileEnum.moveNext()){
        //Get current file
        context.fileObj = fso.GetFile(fileEnum.item());

        //Invoke provided perFile callback function with current context
        var cbResult = Boolean(actionPerFileCallback(context));
        if (failOnCallbackResult(cbResult)){
            return false;
        }
     }

     //Recurse thru subfolders
     if(recursive){
         //Step into sub folder
         for(var subFolderEnum = new Enumerator(context.folderObj.SubFolders); !subFolderEnum.atEnd(); subFolderEnum.moveNext()){
             var subFolderObj = fso.GetFolder(subFolderEnum.item());

             //New calling context that will be passed into recursive call
             var newCallingContext;

             //Provide caller a chance to update the calling context with the new subfolder before making the recursive call
             if(updateContextFn != null){
                 newCallingContext = updateContextFn(subFolderObj, callingContext); 
             }

             //Make recursive call
             var cbResult = iterateFiles(subFolderObj.Path, true, actionPerFileCallback, actionPerFolderCallback, useFnReturnValue, newCallingContext, updateContextFn);
             if (failOnCallbackResult(cbResult)){
                 return false;
             }
         }
     }
     return true; //if we made it here, then all callbacks were successful 
 };

用法:

//Note: The 'lib' object used below is just a utility library I'm using.
function copyFolder(fromPath, toPath, overwrite, recursive){

    var actionPerFileCallback = function(context){
        var destinationFolder = context.callingContext.toPath;
        var destinationPath = lib.buildPath([context.callingContext.toPath, context.fileObj.Name]);
        lib.createFolderIfDoesNotExist(destinationFolder);
        return copyFile(context.fileObj.Path, destinationPath, context.callingContext.overwrite);
    };

    var actionPerFolderCallback = function(context){
        var destinationFolder = context.callingContext.toPath;
        return lib.createFolderIfDoesNotExist(destinationFolder);
    };

    var callingContext = {
        fromPath : fromPath,
        toPath : lib.buildPath([toPath, fso.GetFolder(fromPath).Name]), //include folder in copy
        overwrite : overwrite,
        recursive : recursive
    };

    var updateContextFn = function(currentFolderObj, previousCallingContext){
        return {
            fromPath : currentFolderObj.Path,
            toPath : lib.buildPath([previousCallingContext.toPath, currentFolderObj.Name]), 
            overwrite : previousCallingContext.overwrite,
            recursive : previousCallingContext.recursive
        }
    }
    return iterateFiles(fromPath, recursive, actionPerFileCallback, null, true, callingContext, updateContextFn);
};

我知道这个问题已经过时了,但我偶然发现了它,希望我的回答可以帮助别人!