Skip to content

Instantly share code, notes, and snippets.

@ganeshh123
Last active August 18, 2020 21:21
Show Gist options
  • Save ganeshh123/4bec064dfc507515ce36b47c10e0ef48 to your computer and use it in GitHub Desktop.
Save ganeshh123/4bec064dfc507515ce36b47c10e0ef48 to your computer and use it in GitHub Desktop.
Recursively Delete a folder and it's files in node, with an array of excluded files
let fileSystem = require('fs')
let path = require('path')
/* Returns true if folder is empty, false if not */
folder_empty = (path) => {
return fileSystem.readdirSync(path).length === 0;
}
/* Recursively Deletes a folder and it's contents */
// targetPath = absolute path of folder to be deleted
// exclusions = array of string file names to not delete
let removeDir = (targetPath, exclusions) => {
if (fileSystem.existsSync(targetPath)) {
/* Ensure that files from exclusions array are not deleted */
let filesToDelete = fileSystem.readdirSync(targetPath).filter((file) => {
if(exclusions){
return !exclusions.includes(file)
}else{
return file
}
}
)
/* Recursive Deletion of Folders and Containing Files */
/* If there are still files in the target folder to delete */
if (filesToDelete.length > 0) {
/* If filename is a folder, then recursively run function on that folder, otherwise delete the file */
filesToDelete.forEach( (filename) => {
if (fileSystem.statSync(targetPath + "/" + filename).isDirectory()) {
removeDir(path.join(targetPath, filename), exclusions)
} else {
fileSystem.unlinkSync(path.join(targetPath, filename))
}
})
/* Delete the folder now that it contains no files */
if(targetPath != process.cwd()){
try{
if(folder_empty(targetPath)){
fileSystem.rmdirSync(targetPath)
}
}
catch(err){
console.log(err)
}
}
} else {
/* Delete the folder now that it contains no files */
if(targetPath != process.cwd()){
try{
if(folder_empty(targetPath)){
fileSystem.rmdirSync(targetPath)
}
}
catch(err){
console.log(err)
}
}
}
}
}
module.exports = removeDir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment