NodeJs 生成指定目录中的所有子目录的 txt 格式的报告文档

源码:

// 文件路径:folder-report.js
/**
 * NodeJs 生成指定目录中的所有子目录的 txt 格式的报告文档
 * 功能:生成指定目录中的所有子目录的 txt 格式的报告文档
 * 使用:node folder-report.js
 * 扩展包:无
 */

// 引用 fs 文件系统模块
const NmFs = require('fs');
// 引用 path 路径处理模块
const NmPath = require('path');


/**
 * 生成文件报告指定目录
 * @param {String} fromDir 来源目录
 */
async function reportDirs(fromDir) {
    let filesData = [];
    if (!NmFs.existsSync(fromDir)) {
        console.log('path not exists: ', fromDir);
        return filesData;
    }
    // 自动补齐路径符
    const SEP = NmPath.sep;
    if (!fromDir.endsWith(SEP)) {
        fromDir += SEP;
    }
    // 打开目录
    const dir = await NmFs.promises.opendir(fromDir);
    // 声明变量,优化内存
    let currentPath = '';
    for await (const dirent of dir) {
        // 当前路径
        currentPath = fromDir + dirent.name;
        // 如果不是目录则跳过
        if (!dirent.isDirectory()) {
            continue;
        }
        // 获取目录名称
        filesData.push(NmPath.basename(dirent.name));
    }
    return filesData;
}

// 执行生成报告文件的功能
async function run(fromDir, reportFilePath) {
    let files = await reportDirs(fromDir).catch(err => console.log(err))
    NmFs.writeFileSync(reportFilePath, files.join("\n"));
    console.log('报表已成功生成。详见: ', reportFilePath);
}

// 注意:运行时需修改一下路径信息
const DIR_PATH = 'F:\\Downloads\\Images\\风景';
const REPORT_FILE_PATH = DIR_PATH + '\\' + NmPath.basename(DIR_PATH) + ' 目录.txt';
// 运行入口
run(DIR_PATH, REPORT_FILE_PATH);

运行:

node folder-report.js
posted on 2021-02-25 20:15  sochishun  阅读(339)  评论(0编辑  收藏  举报