zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    Relax! It's just a game(排列组合,简单)
    Feynman(数学)
    The Center of Gravity(一道很很简单的几何题)
    Game with points(数学,难度中)
    Tempter of the Bone(DFS + 奇偶剪枝,好题)
    [置顶] Card
    Find Terrorists(素数筛选+素因子分解)
    Enemy at the Gateway
    Anindilyakwa(简单)
    ACMer(数学,有意思)
  • 原文地址:https://www.cnblogs.com/sochishun/p/14455071.html
Copyright © 2011-2022 走看看