node.js fs.readdir recursive directory search

前端 未结 30 1569
醉酒成梦
醉酒成梦 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:28

    Using bluebird promise.coroutine:

    let promise = require('bluebird'),
        PC = promise.coroutine,
        fs = promise.promisifyAll(require('fs'));
    let getFiles = PC(function*(dir){
        let files = [];
        let contents = yield fs.readdirAsync(dir);
        for (let i = 0, l = contents.length; i < l; i ++) {
            //to remove dot(hidden) files on MAC
            if (/^\..*/.test(contents[i])) contents.splice(i, 1);
        }
        for (let i = 0, l = contents.length; i < l; i ++) {
            let content = path.resolve(dir, contents[i]);
            let contentStat = yield fs.statAsync(content);
            if (contentStat && contentStat.isDirectory()) {
                let subFiles = yield getFiles(content);
                files = files.concat(subFiles);
            } else {
                files.push(content);
            }
        }
        return files;
    });
    //how to use
    //easy error handling in one place
    getFiles(your_dir).then(console.log).catch(err => console.log(err));
    

提交回复
热议问题