best way to get folder and file list in Javascript

前端 未结 4 596
太阳男子
太阳男子 2020-12-05 14:03

I\'m using node-webkit, and am trying to have a user select a folder, and I\'ll return the directory structure of that folder and recursively get its children.

I\'v

4条回答
  •  执笔经年
    2020-12-05 14:32

    I don't like adding new package into my project just to handle this simple task.

    And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.

    So I made a function to get all the folder content (and its sub folder).... NON-Recursively

    var getDirectoryContent = function(dirPath) {
        /* 
            get list of files and directories from given dirPath and all it's sub directories
            NON RECURSIVE ALGORITHM
            By. Dreamsavior
        */
        var RESULT = {'files':[], 'dirs':[]};
    
        var fs = fs||require('fs');
        if (Boolean(dirPath) == false) {
            return RESULT;
        }
        if (fs.existsSync(dirPath) == false) {
            console.warn("Path does not exist : ", dirPath);
            return RESULT;
        }
    
        var directoryList = []
        var DIRECTORY_SEPARATOR = "\\";
        if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;
    
        directoryList.push(dirPath); // initial
    
        while (directoryList.length > 0) {
            var thisDir  = directoryList.shift(); 
            if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;
    
            var thisDirContent = fs.readdirSync(thisDir);
            while (thisDirContent.length > 0) { 
                var thisFile  = thisDirContent.shift(); 
                var objPath = thisDir+thisFile
    
                if (fs.existsSync(objPath) == false) continue;
                if (fs.lstatSync(objPath).isDirectory()) { // is a directory
                    let thisDirPath = objPath+DIRECTORY_SEPARATOR; 
                    directoryList.push(thisDirPath);
                    RESULT['dirs'].push(thisDirPath);
    
                } else  { // is a file
                    RESULT['files'].push(objPath); 
    
                } 
            } 
    
        }
        return RESULT;
    }
    

    the only drawback of this function is that this is Synchronous function... You have been warned ;)

提交回复
热议问题