Skip to content

Instantly share code, notes, and snippets.

@laazebislam
Last active September 8, 2022 08:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save laazebislam/845e61a18541255c0a29eeeb4e0141f4 to your computer and use it in GitHub Desktop.
Save laazebislam/845e61a18541255c0a29eeeb4e0141f4 to your computer and use it in GitHub Desktop.
Node Js Directory remove
var fs = require("fs");
var rmDir = function(dir, rmSelf) {
var files;
rmSelf = (rmSelf === undefined) ? true : rmSelf;
dir = dir + "/";
try { files = fs.readdirSync(dir); } catch (e) { console.log("!Oops, directory not exist."); return; }
if (files.length > 0) {
files.forEach(function(x, i) {
if (fs.statSync(dir + x).isDirectory()) {
rmDir(dir + x);
} else {
fs.unlinkSync(dir + x);
}
});
}
if (rmSelf) {
// check if user want to delete the directory ir just the files in this directory
fs.rmdirSync(dir);
}
}
// Example rmDir("file1") => delete directory with all files || rmDir("file1", false) => delete just the files in the directory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment