如何使用nodejs批量删除文件夹及文件


适用场景: 当一个文件夹中需要在多个地方删除某个文件夹或者文件时,鼠标操作较为繁琐. 这时可以通过nodejs的文件系统进行操作.

  正文:于是在参考某个网友代码基础上进行修改,实现批量删除一个文件夹中的某个文件夹或文件.废话不多说,直接上代码:

---------------------------------------------------------------------------------------------------

let fs = require('fs'); // 引入fs模块
 
function deleteall(path) {
    let files = [];
    if(fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function (file, index) {
            // console.log(file);
            let curPath = path + "/" + file;
            console.log(curPath);
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteall(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};
function findFile(path, findName) {
    let filesAll = [];
    if (fs.existsSync(path)) {
        filesAll = fs.readdirSync(path);
        filesAll.forEach((fileItem,index) => {
            let findCurrPath = path + '/' + fileItem;
            if (fileItem == findName) {
                console.log(findCurrPath);
                deleteall(findCurrPath);
                findFile(path,findName);
            } else {
                if(fs.statSync(findCurrPath).isDirectory()) { // recurse
                    findFile(findCurrPath,findName);
                } 
}
        })
    }
}

findFile('文件夹绝对路径','文件名或文件夹名')
----------------------------------------------------------------------------------------------
 
如何使用:  
  1.第一步:  创建一个js文件,将代码copy进去 
  2.第二步:   在该js文件目录下,打开 CMD 窗口     // 运行前需要将文件夹路径需要更改
  3.第三步:  输入 '' node   js文件名 ''   然后回车
  4.第四步:  运行成功,删除文件成功
  好了!
  到此文件删除成功,如有帮助麻烦点个赞,谢谢!!!
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM