Skip to content

Instantly share code, notes, and snippets.

@liangzan
Created February 2, 2011 14:12
Show Gist options
  • Save liangzan/807712 to your computer and use it in GitHub Desktop.
Save liangzan/807712 to your computer and use it in GitHub Desktop.
A Node.js script to remove all files in a directory recursively
var fs = require('fs')
, path = require('path')
, _ = require('underscore');
var rootPath = "/path/to/remove";
removeDirForce(rootPath);
// path should have trailing slash
function removeDirForce(dirPath) {
fs.readdir(dirPath, function(err, files) {
if (err) {
console.log(JSON.stringify(err));
} else {
if (files.length === 0) {
fs.rmdir(dirPath, function(err) {
if (err) {
console.log(JSON.stringify(err));
} else {
var parentPath = path.normalize(dirPath + '/..') + '/';
if (parentPath != path.normalize(rootPath)) {
removeDirForce(parentPath);
}
}
});
} else {
_.each(files, function(file) {
var filePath = dirPath + file;
fs.stat(filePath, function(err, stats) {
if (err) {
console.log(JSON.stringify(err));
} else {
if (stats.isFile()) {
fs.unlink(filePath, function(err) {
if (err) {
console.log(JSON.stringify(err));
}
});
}
if (stats.isDirectory()) {
removeDirForce(filePath + '/');
}
}
});
});
}
}
});
}
@dudeman9801
Copy link

@iserdmi Thanks. I needed a version that wouldn't delete the directory itself.

@vmengh
Copy link

vmengh commented Apr 21, 2021

Maybe it will be usefull for someone. Extend @guybedfrod function, to remove all in dir but not dir itself.

    rmDir = function(dirPath, removeSelf) {
      if (removeSelf === undefined)
        removeSelf = true;
      try { var files = fs.readdirSync(dirPath); }
      catch(e) { return; }
      if (files.length > 0)
        for (var i = 0; i < files.length; i++) {
          var filePath = dirPath + '/' + files[i];
          if (fs.statSync(filePath).isFile())
            fs.unlinkSync(filePath);
          else
            rmDir(filePath);
        }
      if (removeSelf)
        fs.rmdirSync(dirPath);
    };

Call rmDir('path/to/dir') to remove all inside dir and dir itself. Call rmDir('path/to/dir', false) to remove all inside, but not dir itself.

This is helpful. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment