Node 删除目录

深度优先删除

let fs = require('fs');
let path = require('path');

function rmdir(dir,cb) {
  fs.readdir(dir,function (err, files) {
    next(0);
    function next(index) {
      if(index == files.length) {
        return fs.rmdir(dir,cb);
      }

      let newPath = path.join(dir,files[index]);
      fs.stat(newPath,function (err, stats) {
        if(err){
          console.log(err);
        }
        if(stats && stats.isDirectory()){
          rmdir(newPath,()=>next(index+1));
        } else {
          fs.unlink(newPath,function (err) {
            if (err) {
              console.error(err);
            }
            next(index + 1);
          });
        }
      })
    }
  })
}

let dirPath = '/home/w/ImJoyApp/'

rmdir(dirPath, function () {
  if (fs.existsSync(dirPath)) {
    // delete soft links
    fs.readdir(dirPath,function (err, files) {
      if (err) {
        console.log(err)
      } else {
        rmdir(dirPath ,function () {
          console.log('delete success')
        })
      }
    })  
  } else {
    console.log('delete success')  
  }
})

你可能感兴趣的:(Node 删除目录)