Skip to content

Instantly share code, notes, and snippets.

@UziTech
Created December 9, 2016 05:14
Show Gist options
  • Save UziTech/a69592e927a5c8cd3c21a3ceb1fc4d80 to your computer and use it in GitHub Desktop.
Save UziTech/a69592e927a5c8cd3c21a3ceb1fc4d80 to your computer and use it in GitHub Desktop.
Remove a file or directory recursively
const fs = require("fs");
const path = require("path");
function rimraf(dir) {
return new Promise(function (resolve, reject) {
fs.lstat(dir, function (err, stats) {
if (err) return reject(err);
if (stats.isDirectory()) {
fs.readdir(dir, function (err, files) {
if (err) return reject(err);
Promise.all(files.map(function (file) {
return rimraf(path.join(dir, file));
})).then(function () {
fs.rmdir(dir, function (err) {
if (err) return reject(err);
resolve();
});
}).catch(reject);
});
} else {
fs.unlink(dir, function (err) {
if (err) return reject(err);
resolve();
});
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment