node批量删除文件夹/文件

 

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('文件夹绝对路径','文件名或文件夹名')
findFile('I:\\workspace', 'node_modules')

 

posted @ 2021-12-19 18:52  Dz&Ying  阅读(524)  评论(0)    收藏  举报