node.js fs.readdir recursive directory search

前端 未结 30 1877
醉酒成梦
醉酒成梦 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条回答
  •  渐次进展
    2020-11-22 16:19

    With Recursion

    var fs = require('fs')
    var path = process.cwd()
    var files = []
    
    var getFiles = function(path, files){
        fs.readdirSync(path).forEach(function(file){
            var subpath = path + '/' + file;
            if(fs.lstatSync(subpath).isDirectory()){
                getFiles(subpath, files);
            } else {
                files.push(path + '/' + file);
            }
        });     
    }
    

    Calling

    getFiles(path, files)
    console.log(files) // will log all files in directory
    

提交回复
热议问题