Skip to content

Instantly share code, notes, and snippets.

@thetrompf
Last active December 15, 2015 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thetrompf/5244858 to your computer and use it in GitHub Desktop.
Save thetrompf/5244858 to your computer and use it in GitHub Desktop.
fs.rmrf = (dir, callback) ->
# test if the directory exists.
fs.exists dir, (exists) ->
# return if the directory already is gone.
return callback null unless exists
fs.stat dir, (err, stats) ->
# return if an error occured.
return callback err if err
# unlink if it is a file, else continue, the recursive call.
return fs.unlink dir, callback unless stats.isDirectory()
# reading the files in the next directory.
count = 0
fs.readdir dir, (err, files) ->
# return if an error occurs.
return callback err if err
# remove the directory if it's empty.
return fs.rmdir dir, callback if files.length < 1
# remove the files and directories recursively.
files.forEach (file) ->
sub = path.join dir, file
rmrf sub, (err) ->
# return if an error occured.
return callback err if err
# remove directories.
fs.rmdir dir, callback if ++count is files.length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment