node.js fs.readdir recursive directory search

前端 未结 30 1896
醉酒成梦
醉酒成梦 2020-11-22 15:55

Any ideas on an async directory search using fs.readdir? I realise that we could introduce recursion and call the read directory function with the next directory to read, bu

30条回答
  •  旧时难觅i
    2020-11-22 16:31

    Just in case anyone finds it useful, I also put together a synchronous version.

    var walk = function(dir) {
        var results = [];
        var list = fs.readdirSync(dir);
        list.forEach(function(file) {
            file = dir + '/' + file;
            var stat = fs.statSync(file);
            if (stat && stat.isDirectory()) { 
                /* Recurse into a subdirectory */
                results = results.concat(walk(file));
            } else { 
                /* Is a file */
                results.push(file);
            }
        });
        return results;
    }
    

    Tip: To use less resources when filtering. Filter within this function itself. E.g. Replace results.push(file); with below code. Adjust as required:

        file_type = file.split(".").pop();
        file_name = file.split(/(\\|\/)/g).pop();
        if (file_type == "json") results.push(file);
    

提交回复
热议问题