node.js fs.readdir recursive directory search

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

    Using async/await, this should work:

    const FS = require('fs');
    const readDir = promisify(FS.readdir);
    const fileStat = promisify(FS.stat);
    
    async function getFiles(dir) {
        let files = await readDir(dir);
    
        let result = files.map(file => {
            let path = Path.join(dir,file);
            return fileStat(path).then(stat => stat.isDirectory() ? getFiles(path) : path);
        });
    
        return flatten(await Promise.all(result));
    }
    
    function flatten(arr) {
        return Array.prototype.concat(...arr);
    }
    

    You can use bluebird.Promisify or this:

    /**
     * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
     *
     * @param {Function} nodeFunction
     * @returns {Function}
     */
    module.exports = function promisify(nodeFunction) {
        return function(...args) {
            return new Promise((resolve, reject) => {
                nodeFunction.call(this, ...args, (err, data) => {
                    if(err) {
                        reject(err);
                    } else {
                        resolve(data);
                    }
                })
            });
        };
    };
    

    Node 8+ has Promisify built-in

    See my other answer for a generator approach that can give results even faster.

提交回复
热议问题