javascript使用promise递归读取目录下所有文件

转载自bdss58的博文,原文地址:https://blog.csdn.net/bdss58/article/details/51377577

var fs = require('fs');
var path = require('path');

function readdirPromisify(dir) {
    return new Promise((resolve, reject) => {
        fs.readdir(dir, (err, list) => {
            if (err) {
                reject(err);
            }
            resolve(list);
        });
    });
}

function statPromisify(dir) {
    return new Promise((resolve, reject) => {
        fs.stat(dir, (err, stats) => {
            if (err) {
                reject(err);
            }
            resolve(stats);
        });
    });
}

function listDir(dir) {
    return statPromisify(dir).then(stats => {
        if (stats.isDirectory()) {
            return readdirPromisify(dir).then(list => 
                Promise.all(list.map(item => 
                    listDir(path.resolve(dir, item))
                ))
            ).then(subtree => [].concat(...subtree));
        } else {
            return [dir];
        }
    });
}

你可能感兴趣的:(nodejs)