前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >工具函数 – 获取项目文件夹内所有文件

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

作者头像
上山打老虎了
发布2022-06-15 08:55:35
6270
发布2022-06-15 08:55:35
举报
文章被收录于专栏:Article

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

代码语言:javascript
复制
'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;
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年05月04日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档