工具函数 – 获取项目文件夹内所有文件

对于.开头的隐藏文件也会被读取到。

'use strict';

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readdirPromise = promisify(fs.readdir);
const statPromise = promisify(fs.stat);

class File {
    constructor(filename, size) {
        this.filename = filename;
        this.size = size;
    }
}


function scanFs() {
    const dir = process.cwd();
    const result = [];

    function collect(dir) {
        const basedir = dir;
        return readdirPromise(dir).then(files =>
            Promise.all(files.map(fn => {
                const fullpath = path.join(dir, fn);
                const realpath = path.relative(basedir, fullpath);

                return statPromise(fullpath).then(stats => {
                    if (stats.isDirectory()) {
                        return collect(fullpath);
                    }

                    const file = new File(realpath, stats.size)
                    result.push(file)
                })
            }))
        )
    }
    return collect(dir).then(() => result);
}

module.exports = scanFs;