node.js fs.readdir recursive directory search

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

    Another simple and helpful one

    function walkDir(root) {
        const stat = fs.statSync(root);
    
        if (stat.isDirectory()) {
            const dirs = fs.readdirSync(root).filter(item => !item.startsWith('.'));
            let results = dirs.map(sub => walkDir(`${root}/${sub}`));
            return [].concat(...results);
        } else {
            return root;
        }
    }
    

提交回复
热议问题