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
    
  • 相关阅读:
    Maven setting配置镜像仓库
    MyBatis配置Mapping,JavaType和JDBCType的对应关系,#与$区别
    Git常用命令
    Js JSON.stringify()与JSON.parse()与eval()详解及使用案例
    例:判断是不是自有属性hasOwnProperty方法
    JS中原型链中的prototype与_proto_的个人理解与详细总结
    原型理解:prototype
    JS中attribute和property的区别
    面试题术语
    函数语法
  • 原文地址:https://www.cnblogs.com/sochishun/p/14455071.html
Copyright © 2011-2022 走看看