当前位置:网站首页>Tool functions – get all files in the project folder

Tool functions – get all files in the project folder

2022-06-24 08:15:00 Mr. Zirun

about . The first hidden file will also be read .

'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;
原网站

版权声明
本文为[Mr. Zirun]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210628105202552x.html