NodeJs 递归所有子目录,删除指定的文件

// 文件路径:file-remove.js
/**
 * NodeJs 递归删除目录中的指定文件
 * 功能:递归所有子目录,删除指定文件名的文件
 * 使用:node file-remove.js
 * 扩展包:无
 */

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

// 配置信息
const config = {
    files: ['获取更多免费资源.txt', '电子书大全.url', '更多目录.png'],
}

/**
 * 递归删除文件
 * @param {String} fromDir 来源目录
 */
async function removeFiles(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 basename = '',
        currentPath = '';
    for await (const dirent of dir) {
        // 当前路径
        currentPath = fromDir + dirent.name;
        // 处理目录
        if (dirent.isDirectory()) {
            // 如果当前路径是目录,则进入递归模式
            await removeFiles(currentPath + SEP);
            continue;
        }
        // 处理文件
        basename = NmPath.basename(dirent.name); // 带扩展名
        if (config.files.indexOf(basename) > -1) {
            NmFs.unlinkSync(currentPath);
            console.log('删除文件', currentPath);
        }
    }
    return filesData;
}

// 注意:运行时需修改一下路径信息
const DIR_PATH = 'F:\\Downloads\\Books';
// 运行入口
removeFiles(DIR_PATH);

运行:

node file-remove.js
posted on 2021-02-27 11:06  sochishun  阅读(677)  评论(0编辑  收藏  举报