Is node.js rmdir recursive ? Will it work on non empty directories?

后端 未结 22 1411
清歌不尽
清歌不尽 2021-01-31 13:41

The documentation for fs.rmdir is very short and doesn\'t explain the behavior of rmdir when the directory is not empty.

Q: What happens if I try to use

22条回答
  •  逝去的感伤
    2021-01-31 14:03

    Here is an asynchronous recursive version that works with promises. I use the 'Q' library but anyone will do with a few changes (eg the 'fail' function).

    To make use of it, we must make a few simple wrappers around some core Node functions, namely fs.stat, fs.readdir, fs.unlink and fs.rmdir to make them promise-friendly.

    Here they are:

    function getStat(fpath) {
      var def = Q.defer();
      fs.stat(fpath, function(e, stat) {
        if (e) { def.reject(); } else { def.resolve(stat); }
      });
      return def.promise;
    }
    
    function readdir(dirpath) {
      var def = Q.defer();
      fs.readdir(dirpath, function(e, files) {
        if (e) { def.reject(e); } else { def.resolve(files); }
      });
      return def.promise;
    }
    
    function rmFile(fpath) {
      var def = Q.defer();
      fs.unlink(fpath, function(e) { if(e) { def.reject(e); } else { def.resolve(fpath); }});
      return def.promise;
    }
    
    function rmDir(fpath) {
      var def = Q.defer(); 
      fs.rmdir(fpath, function(e) { if(e) { def.reject(e); } else { def.resolve(fpath); }});
      return def.promise;
    }
    

    So here is the recursive rm function:

    var path = require('path');
    
    function recursiveDelete(fpath) {
      var def = Q.defer();
    
      getStat(fpath)
      .then(function(stat) {
        if (stat.isDirectory()) {
          return readdir(fpath)
          .then(function(files) {
            if (!files.length) { 
              return rmDir(fpath);
            } else {
              return Q.all(files.map(function(f) { return recursiveDelete(path.join(fpath, f)); }))
              .then(function() { return rmDir(fpath); });
            }
          }); 
        } else {
          return rmFile(fpath);
        }
      })
      .then(function(res) { def.resolve(res); })
      .fail(function(e) { def.reject(e); })
      .done();
      return def.promise;
    }
    

提交回复
热议问题