写一个ES6 的遍历目录函数

// npm init
// npm install koa --save-dev
// node --harmony app.js
const fs = require('fs');

var eachDir = (() => {
    let queue = [];
    var eachFiles = (options) => {
        if (queue.length) {
            let path = queue.shift();
            fs.readdir(path, (err, files) => {
                if (err) {
                    options.fail(err);
                    return;
                }

                files.forEach((file, i) => {
                    let url = path + '/' + file;
                    let stats = fs.statSync(url);

                    if (stats.isDirectory()) {
                        queue.push(url);
                    } else {
                        options.callback && options.callback.call(stats, {
                            name: file,
                            size: stats.size,
                            path: url
                        });
                    }
                });

                eachFiles(options);
            });
        } else {
            options.done();
        }
    };

    return (path, options) => {
        let stats = fs.statSync(path);
        if (stats.isDirectory()) {
            queue.push(path);    
        }
        eachFiles(options);
    };
})();

let total = 0, fileTypes = {};
eachDir('./', {
    callback(file) {
        let ret = file.name.match(/\.(\w+$)/);
        if (ret) {
            if (!fileTypes[ret[0]]) {
                fileTypes[ret[0]] = 0;
            }
            fileTypes[ret[0]] += 1;
        }
        // console.log(file);
        total++;
    },
    done() {
        console.log(total, fileTypes);
        fs.writeFile('./result.txt', JSON.stringify(fileTypes), (err) => {
            if (err) throw err;
            console.log('done');
        });
    },
    fail(err) {
        console.log(err);
    }
});
posted @ 2016-08-21 18:40  风之约  阅读(927)  评论(0编辑  收藏  举报