Skip to content

Instantly share code, notes, and snippets.

@AnatoliyLitinskiy
Created March 30, 2018 10:23
Show Gist options
  • Save AnatoliyLitinskiy/6f1a815764ff60a08f52cf9b2b256001 to your computer and use it in GitHub Desktop.
Save AnatoliyLitinskiy/6f1a815764ff60a08f52cf9b2b256001 to your computer and use it in GitHub Desktop.
remove / clean out directory using node.js fs
const fs = require('fs');
const path = require('path');
const async = require('async');
function rmDir(dirPath, cb, removeSelf = true) {
try {
fs.readdir(dirPath, (err, files) => {
if (err) return cb(err);
// run tasks in parallel
async.each(files, (file, cb) => {
try {
const filePath = path.join(dirPath, file);
fs.stat(filePath, (err, stats) => {
if (err) return cb(err);
if (stats.isFile()) {
fs.unlink(filePath, cb);
} else {
rmDir(filePath, cb);
}
});
} catch (err) {
cb(err);
};
}, (err) => {
if (err) return cb(err);
if (removeSelf) {
fs.rmdir(dirPath, cb);
} else {
cb();
}
});
});
} catch(e) {
cb(e);
}
};
const cleanDir = (dirPath, cb) => rmDir(dirPath, cb, false);
module.exports = {
rmDir,
cleanDir,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment