美文网首页
Node 删除目录

Node 删除目录

作者: 草帽lufei | 来源:发表于2019-10-12 19:22 被阅读0次

深度优先删除

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 删除目录

      本文链接:https://www.haomeiwen.com/subject/lrsvtctx.html