Created
July 27, 2012 13:56
-
-
Save greenlieber/3188170 to your computer and use it in GitHub Desktop.
nodejs, delete a folder recursively, async with callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ### removeRecursive | |
// NodeJS: | |
// Delete a file or delete a DIR recursively | |
// be aware that this is a power full delete function | |
// so best is to check if the PATH given is really | |
// the path you want to DELETE ENTIRELY | |
// | |
// ### usage example | |
// remove a folder recursively | |
// | |
// fs.removeRecursive(full_path_to_dir,function(err,status){}); | |
// | |
// or just delete a file (works to) | |
// | |
// fs.removeRecursive(full_path_to_file,function(err,status){}); | |
// | |
var fs = require('fs'); | |
fs.removeRecursive = function(path,cb){ | |
var self = this; | |
fs.stat(path, function(err, stats) { | |
if(err){ | |
cb(err,stats); | |
return; | |
} | |
if(stats.isFile()){ | |
fs.unlink(path, function(err) { | |
if(err) { | |
cb(err,null); | |
}else{ | |
cb(null,true); | |
} | |
return; | |
}); | |
}else if(stats.isDirectory()){ | |
// A folder may contain files | |
// We need to delete the files first | |
// When all are deleted we could delete the | |
// dir itself | |
fs.readdir(path, function(err, files) { | |
if(err){ | |
cb(err,null); | |
return; | |
} | |
var f_length = files.length; | |
var f_delete_index = 0; | |
// Check and keep track of deleted files | |
// Delete the folder itself when the files are deleted | |
var checkStatus = function(){ | |
// We check the status | |
// and count till we r done | |
if(f_length===f_delete_index){ | |
fs.rmdir(path, function(err) { | |
if(err){ | |
cb(err,null); | |
}else{ | |
cb(null,true); | |
} | |
}); | |
return true; | |
} | |
return false; | |
}; | |
if(!checkStatus()){ | |
for(var i=0;i<f_length;i++){ | |
// Create a local scope for filePath | |
// Not really needed, but just good practice | |
// (as strings arn't passed by reference) | |
(function(){ | |
var filePath = path + '/' + files[i]; | |
// Add a named function as callback | |
// just to enlighten debugging | |
fs.removeRecursive(filePath,function removeRecursiveCB(err,status){ | |
if(!err){ | |
f_delete_index ++; | |
checkStatus(); | |
}else{ | |
cb(err,null); | |
return; | |
} | |
}); | |
})() | |
} | |
} | |
}); | |
} | |
}); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment